0

I have coded for add and remove input text fields dynamically in AngularJS. Here is my code:

My HTML

<div class="form-group">
    <label for="hobbies">Hobbies</label>
    <span ng-repeat="hobby in hobbies track by $index">
        <div class="form-group">
            <input type='text' ng-model='hobbies[$index]' class="form-control pull-right"/>
            <button ng-click = "addHobby()" ng-show="$last">+</button>
            <button ng-click = "removeHobby($index)" ng-show="hobbies.length > 1">-</button>
        </div>
    </span>
</div>

Angular Controller

$scope.hobbies = [''];

$scope.addHobby = function() {
    $scope.hobbies.push('');
}

$scope.removeHobby = function(index) {
    if(index >= 0){
        $scope.hobbies.splice(index, 1);
    }
}

In this how can I validate empty text fields whenever I click on + button?

1
  • In the addHobby function, you could add a check for empty fields Commented Sep 28, 2017 at 7:47

1 Answer 1

1

Change your addhobby function to something can validate empty text fields, like:

$scope.addHobby = function($index) {
    if($scope.hobbies[$index])
        $scope.hobbies.push('');
}

and your html button to:

<button ng-click = "addHobby($index)" ng-show="$last">+</button>

This way your addHobby function will add an hobby whenever your current input text field it's not empty.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually he down't even need the index since it's always the last

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.