0

I'm building an order form with multiple select elements added dynamically. The validation is handled by Angular, however validation breaks on cloned elements. Here's a Plunkr

http://plnkr.co/edit/TqofTw6K7nvLJzPEYAi3?p=preview

isharko
  • 90
  • 11
  • See this: http://stackoverflow.com/questions/14378401/dynamic-validation-and-name-in-a-form-with-angularjs Short story: looks like there are some workarounds for 1.2x angular, or try out 1.3? – aet May 06 '14 at 01:05

2 Answers2

0

Don't clone the elements, that's not the angular way to do this...

Instead use an ng-repeat directive to loop through the items you wish to collect.

As for form validations, please refer to this article about validating each item individually by using ng-form

Brocco
  • 62,737
  • 12
  • 70
  • 76
0

As what Brocco mentioned, cloning the elements won't be the angular way of doing this. You can do it by following these steps:

  1. Create an array to hold all the newly added <select> items. e.g. $scope.dataArray = []
  2. Wrap each form items with an ng-form together with an ng-repeat, be sure to use this notation:

    <div ng-repeat="data in dataArray track by $index" ng-form="dataForm"></div>

    to avoid ng-repeat duplicates.

  3. Create a scope function to add a new dataArray item, similar to your cloning function. e.g:

    $scope.addItem = function() { $scope.dataArray.push({}) }

  4. Use dataArray[$index].name as the model to get a direct reference of each item in the dataArray array

HTML

        <div ng-repeat="data in dataArray track by $index" ng-form="dataForm">
          <div class="item">
            <div class="form-group" ng-class="{ 'has-error' : dataForm.name.$invalid && submitted }">
                <label>Name</label>
                <select id="name" name="name"  ng-model="dataArray[$index].name" 
                          ng-options="item as item.name for item in items" required></select>
                <p ng-show="dataForm.name.$invalid && dataForm.name.$pristine && submitted" class="help-block">You name is required.</p>
            </div>
            <span class="btn btn-success" ng-click="addItem()"> Add </span> 
          </div>
        </div>

JAVASCRIPT

  $scope.dataArray = [{}];

  $scope.items = [
          { name: 'Protein 1' },
          { name: 'Protein 2' },
          { name: 'Protein 3' },
          { name: 'Protein 4' },
          { name: 'Protein 5' }
  ];

  $scope.addItem = function() {
    $scope.dataArray.push({})
  }

See this plunker update.

ryeballar
  • 29,658
  • 10
  • 65
  • 74