将复选框绑定到AngularJs中的对象值 [英] Binding checkboxes to object values in AngularJs

查看:53
本文介绍了将复选框绑定到AngularJs中的对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在于将复选框(选中/未选中)的状态绑定到对象值.

The problem is in binding the state of the checkbox (checked/unchecked) to the object values.

HTML:

<div ng:controller="Ctrl"> 
   <div ng:repeat="(letter, number) in obj">
     {{letter}} and {{number}}
     <input type="checkbox" ng:model="obj[letter]">
</div>    

控制器:

function Ctrl() {
    this.obj = {a:true,b:true};    
};​

单击第一个复选框会影响第二个复选框的状态,但是模型正确,因此obj变为{a:false,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}.

可以在以下位置找到示例 http://jsfiddle.net/alexpetrov/tRxzr/

Example can be found at http://jsfiddle.net/alexpetrov/tRxzr/

该如何解决?

推荐答案

绑定ng-repeat对象而不是原始类型.

Bind ng-repeat to objects rather than primitive types.

function Ctrl() {
    this.obj = [{id: 'a', checked: true}, {id: 'b', checked: true}];
}

http://jsfiddle.net/tRxzr/1/

绑定到原始类型会混淆ng-repeat,这是一个错误: https://github.com/angular/angular.js/issues/933

Binding to primitive types confuses ng-repeat, it's a bug: https://github.com/angular/angular.js/issues/933

这篇关于将复选框绑定到AngularJs中的对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆