Simon Green
Simon Green

Reputation: 1161

Validating repeating inputs inside an AngularJS form

I know this has been asked before, and have even found a well-upvoted answer here:

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

But I can't get that solution to work. I've got an example here - annoyingly both jsFiddle and Plunkr seem to be down right now.

Here's the JS:

app.controller('DetailsCtrl', ['$scope', function($scope) {
    $scope.loading = false;
    $scope.formData = {
        lines: [{
            text: 'test.com'}]
    };
    $scope.addRow = function() {
      $scope.formData.lines.push({text:null});

    };
}]);

Here's the markup:

<body ng-controller="DetailsCtrl">
  <div>
    <form name="mainForm" novalidate class="form-vertical">
...some non-repeating inputs go in here...
      <div data-ng-repeat="line in formData.lines" data-ng-form="lineForm">

          <input type="text" name="myinput" data-ng-model="line.text" data-ng-required="true">
          <span data-ng-show="mainForm.lineForm.myinput.$error.required">Error!</span>


      </div>

      <a href='#' data-ng-click="addRow()">New Line</a>
    </form>
  </div>


</body>

You'll notice initially there is one text input with text in - great. Click the 'New Line' link. Because the new text input fails validation - BOTH text inputs get the warning span shown... I just want the one span relating to the one empty text input to show up.

Upvotes: 1

Views: 547

Answers (1)

dubadub
dubadub

Reputation: 3342

As AngularJS relays on input names to expose validation errors, and you used the same name for all inputs, you faced with this effect.

So you can't generate input name dynamically, but instead you can use ng-form (see https://docs.angularjs.org/api/ng/directive/ngForm).

<form name="mainForm" novalidate class="form-vertical">...some non-repeating inputs go in here...
    <div data-ng-repeat="line in formData.lines" data-ng-form="lineForm">
        <input type="text" name="myinput" data-ng-model="line.text" data-ng-required="true"> 
        <span data-ng-show="lineForm.myinput.$error.required">Error!</span>    
    </div> <a href='#' data-ng-click="addRow()">New Line</a>

</form>

EDIT. Please note, access to error myinput.$error.required instead of lineForm.myinput.$error.required.

Please, checkout working fiddle http://jsfiddle.net/Y9g4q/7/.

Upvotes: 1

Related Questions