AngularJS:ng-repeat 中的 ng-model? [英] AngularJS: ng-model inside ng-repeat?
问题描述
我正在尝试使用 ng-repeat 生成表单输入.注意:'customFields' 是一个字段名称数组:["Age", "Weight", "Ethnicity"].
<label class="control-label">{{field}}</label><div class="控件"><input type="text" ng-model="person.customfields.{{field}}"/>
设置ng-model"的最佳/正确方法是什么?我想将它作为 person.customfields.'fieldname' 发送到服务器,其中 fieldname 来自 'field in customFields'.
<div class="control-group" ng-repeat="customFields 中的字段"><label class="control-label">{{field}}</label><div class="控件"><input type="text" ng-model="person.customfields[field]"/>
<button ng-click="collectData()">Collect</button>
功能Ctrl($范围){$scope.customFields = ["年龄", "体重", "种族"];$scope.person = {自定义字段:{年龄":0,权重":0,种族":0}};$scope.collectData = 函数 () {控制台日志($scope.person.customfields);}}
您可以在这里尝试一下.
更新:
对于验证,诀窍是将
放在转发器中.请尝试.
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'.
<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.
这篇关于AngularJS:ng-repeat 中的 ng-model?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!