AngularJS: ng-model inside ng-repeat?

泪湿孤枕 提交于 2019-11-27 05:36:45

问题


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'.


回答1:


<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.




回答2:


It should be:

<input type="text" ng-model="person.customfields[field]" />



回答3:


Any on who ends up here For ng-model inside ng-repeat

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

the above link has good description on how to use it with examples




回答4:


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



来源:https://stackoverflow.com/questions/17865785/angularjs-ng-model-inside-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!