javascript 将复选框绑定到 AngularJs 中的对象值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10447337/
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 checkboxes to object values in AngularJs
提问by petrov.alex
The problem is in binding the state of the checkbox (checked/unchecked) to the object values.
问题在于将复选框的状态(选中/未选中)绑定到对象值。
HTML:
HTML:
<div ng:controller="Ctrl">
<div ng:repeat="(letter, number) in obj">
{{letter}} and {{number}}
<input type="checkbox" ng:model="obj[letter]">
</div>
?
?
Controller:
控制器:
function Ctrl() {
this.obj = {a:true,b:true};
};?
When the first checkbox is clicked it affects the state of the second checkbox, but the model is correct, so obj becomes {a:false, b:true}.
当第一个复选框被点击时,它会影响第二个复选框的状态,但模型是正确的,因此 obj 变为 {a:false, b:true}。
Example can be found at http://jsfiddle.net/alexpetrov/tRxzr/
可以在http://jsfiddle.net/alexpetrov/tRxzr/找到示例
How to fix this?
如何解决这个问题?
回答by Vojta
Bind ng-repeat to objects rather than primitive types.
将 ng-repeat 绑定到对象而不是原始类型。
function Ctrl() {
this.obj = [{id: 'a', checked: true}, {id: 'b', checked: true}];
}
Binding to primitive types confuses ng-repeat, it's a bug: https://github.com/angular/angular.js/issues/933
绑定到原始类型会混淆 ng-repeat,这是一个错误:https: //github.com/angular/angular.js/issues/933
回答by Rafi Ali Khan
When the JSON is not entirely in your control, you get a primitive array instead of an object. You want to do an ng-repeat on the same.
当 JSON 不完全在您的控制之下时,您将获得一个原始数组而不是一个对象。你想在同样的地方做一个 ng-repeat 。
To bind ng-repeats to checkboxes to a primitive array and get the selected items. See the plunker code here.
将 ng-repeat 绑定到复选框到原始数组并获取所选项目。请参阅此处的 plunker 代码。