AngularJS: ng-model inside ng-repeat?

I am trying to create form input 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 install "ng-model"? I would like to send it to the server as person.customfields.'fieldname ' , where fieldname is obtained from the field in customFields.

+21
angularjs angularjs-ng-repeat angularjs-directive
Jul 25 '13 at 18:19
source share
4 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 verification, the correctness is to put <ng-form> inside the repeater. Please try .

+27
Jul 25 '13 at 22:38
source share

It should be:

 <input type="text" ng-model="person.customfields[field]" /> 
+6
Jul 25 '13 at 18:23
source share

Anyone who ends here. For ng-model inside ng-repeat

http://jsfiddle.net/sirhc/z9cGm/

the link provided has a good description of how to use it with examples

+3
Oct 27 '13 at 12:04 on
source share

Try this ng model = "person.customfields." {{field}} Moved double quotes

-one
Jul 25 '13 at 23:47 on
source share



All Articles