Pergunta

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

Foi útil?

Solução

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.

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top