Reputation: 2428
I'm creating table with nested ng-repeat but checkboxes in each column have synchronous reaction when being checked/unchecked. How to fix this behaviour so each checkbox could be checked on its own?
HTML:
<tr ng-repeat="person in persons | orderBy: 'secondName'">
<td>
{{person.firstName + ' ' + person.secondName}}
</td>
<td ng-repeat="day in person.daysOfWeek">
<input type="checkbox"
name="{{day.name}}"
ng-model='day.checked'/>
</td>
</tr>
Code:
var daysOfWeek = [ { name: 'Sun', checked: '' }
,{ name: 'Mon', checked: '' }
,{ name: 'Tue', checked: '' }
,{ name: 'Wen', checked: '' }
,{ name: 'Thu', checked: '' }
,{ name: 'Fri', checked: '' }
,{ name: 'Sat', checked: ''}];
var persons =
[{ firstName: 'Jil', secondName: 'Mith' }
,{ firstName: 'Alvin', secondName: 'Zurb' }
,{ firstName: 'John', secondName: 'Burt' }
,{ firstName: 'Tom', secondName: 'Kurtz' }];
persons.forEach(function(person) {
person.daysOfWeek = daysOfWeek;
});
angular.module('MyApp',[]);
function MyCtrl($scope) {
$scope.persons = persons;
console.log($scope.persons);
$scope.saveInfo = function() {
console.log($scope.persons);
};
}
Upvotes: 0
Views: 398
Reputation: 5825
You are assigning the same daysOfWeek
array to each person, so when you check a specific day, you check the same object (day) for each person.
You can solve this by mapping a new days of week array to each person, using angular.extend, so you will you get a new day object for each person:
persons.forEach(function(person) {
person.daysOfWeek = daysOfWeek.map(function(day) { return angular.extend({}, day)}); // extending the day object to a new object
});
Chekc this fiddle.
Upvotes: 3