带复选框的嵌套 ng-repeat

Nested ng-repeat with checkboxes

我正在使用嵌套的 ng-repeat 创建 table,但每列中的复选框在 checked/unchecked 时都有同步反应。如何修复此行为以便每个复选框都可以单独选中?

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);
    };
}

The Fiddle is here

您正在为每个人分配相同的 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
});

检查此 fiddle