javascript 在 angularjs 中的 ng-repeat 中使用 ng-model 进行绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16467455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding using ng-model inside ng-repeat in angularjs
提问by shahalpk
I'm trying to bind a model 'User' to a list of input fields. I do not know the fields beforehand, so i've to write a generic code to setup the form based on the fields.
我正在尝试将模型“用户”绑定到输入字段列表。我事先不知道这些字段,所以我必须编写一个通用代码来根据这些字段设置表单。
<script>
function MyController($scope){
$scope.fields = ['name','password','dob'];
$scope.user1 = {name:"Shahal",password:"secret"}
};
</script>
<div ng-app ng-controller="MyController">
<ul>
<li ng-repeat="field in fields">
<label>{{field}}</label><input type="text" ng-model="user1.{{field}}">
</li>
</ul>
<pre>{{fields}}</pre>
</div>
I'm trying to loop through the fields and show a input field for each fields (available in scope). But the binding is not proper as i'm trying to evaluate an expression inside ng-model.
我正在尝试遍历字段并显示每个字段的输入字段(在范围内可用)。但是绑定不正确,因为我正在尝试评估 ng-model 中的表达式。
Basically i'm trying to show 3 input fields (name,password,dob) with the object user1 attached to the corresponding field.
基本上,我试图显示 3 个输入字段(名称、密码、dob),并将对象 user1 附加到相应的字段。
Here's the fiddle
这是小提琴
Any help?
有什么帮助吗?
回答by Ajay Beniwal
Below will solve your problem
下面将解决您的问题
<script>
function MyController($scope){
$scope.fields = ['name','password','dob'];
$scope.user1 = {name:"Shahal",password:"secret"}
};
</script>
<div ng-app ng-controller="MyController">
<ul>
<li ng-repeat="field in fields">
<label>{{field}}</label><input type="text" ng-model="user1[field]">
</li>
</ul>
<pre>{{fields}}</pre>
</div>