我正在使用嵌套的ng-repeat创建表格,但每个列中的复选框在选中/取消选中时都会产生同步反应。如何修复此行为,以便可以单独检查每个复选框?
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>
代码:
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);
};
}
答案 0 :(得分:3)
您正在为每个人分配相同的daysOfWeek
数组,因此当您检查特定日期时,您会检查每个人的相同对象(日期)。
您可以使用angular.extend将新的星期数组映射到每个人,从而解决这个问题,这样您就可以为每个人获得一个新的一天对象:
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。