Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: ng-model inside ng-repeat?

Tags:

I'm trying to generate form inputs with ng-repeat. Note: 'customFields' is an array of field names: ["Age", "Weight", "Ethnicity"].

 <div class="control-group" ng-repeat="field in customFields">    <label class="control-label">{{field}}</label>      <div class="controls">        <input type="text" ng-model="person.customfields.{{field}}" />      </div>  </div> 

What is the best/correct way to set 'ng-model'? I would like to send it to the server as person.customfields.'fieldname' where fieldname comes from 'field in customFields'.

like image 908
502502 Avatar asked Jul 25 '13 18:07

502502


1 Answers

<div ng-app ng-controller="Ctrl">     <div class="control-group" ng-repeat="field in customFields">         <label class="control-label">{{field}}</label>         <div class="controls">             <input type="text" ng-model="person.customfields[field]" />         </div>     </div>     <button ng-click="collectData()">Collect</button> </div>  function Ctrl($scope) {     $scope.customFields = ["Age", "Weight", "Ethnicity"];     $scope.person = {         customfields: {             "Age": 0,                 "Weight": 0,                 "Ethnicity": 0         }     };      $scope.collectData = function () {         console.log($scope.person.customfields);     } } 

You can try it here.

Updated:

For the validation, the trick is to put <ng-form> inside the repeater. Please try.

like image 173
zs2020 Avatar answered Sep 28 '22 08:09

zs2020