ramiromd
ramiromd

Reputation: 2029

Set validation for dynamic field

I have a form where the user can add fields dynamically. It is my html:

<body ng-controller="FruitController">
    <button type="button" ng-click="addFruit()">Add fruit</button>
    <form name="list">
      <div id="dynamicList" ng-repeat="fruit in fruits">
        <input type="text" name="fruitName" ng-model="fruit.name" ng-minlength="3"/>
      </div>
    </form>
</body>

And it is my controller:

app.controller('FruitController', [function(){

  $scope.fruits = [
    {name: 'Apple', color: 'red'} 
  ];

  $scope.addFruit = function()
  {
    $scope.fruits.push({name: '', color: ''});
  };
}]);

So, when a field is invalid i add a css class with the next directive:

ng-class="{'uk-form-danger': (list.fruitName.$invalid && !list.fruitName.$pristine)}"

The problem is that, when 1 field fails, another fields too. Any ideas ?

Upvotes: 2

Views: 112

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Form inside ng-repeat won't work directly. You need to create a a separate form for inner elements that form will be child of outer form list

<form name="list">
  <div id="dynamicList" ng-repeat="fruit in fruits">
   <form name="innerForm">
    <input type="text" name="fruitName" ng-model="fruit.name" ng-minlength="3" 
     ng-class="{'uk-form-danger': (innerForm.fruitName.$invalid && !fruit.name.$pristine)}"/>
   </form>
  </div>
</form>

Upvotes: 1

Related Questions