Binding checkboxes to object values in AngularJs

angularjs, javascript

Solution

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/

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

Problem

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> ``` ​ 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}. Example can be found at http://jsfiddle.net/alexpetrov/tRxzr/ How to fix this?

Original source