javascript - 带复选框的嵌套 ng-repeat

标签 javascript angularjs checkbox nested

我正在创建带有嵌套 ng-repeat 的表,但每列中的复选框在选中/取消选中时都有同步 react 。如何修复此行为,以便可以单独选中每个复选框?

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

关于javascript - 带复选框的嵌套 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856234/

相关文章:

javascript - 获取 Gridview 选中项目的列表

javascript - 如何在 d3 selection().exit() 之后删除父 DOM 节点

javascript - 如何正确地为我的变量创建 for 循环?

javascript - 为什么这个 JavaScript 会失败?

if-statement - angularjs if 语句?

javascript - 没有从 localStorage 获取与保存的变量相同的类型?

css - 如何改变复选框标签的宽度而不影响复选框?

javascript - JS 正则表达式执行分隔符之间的内部字符串并检查损坏的分隔符

javascript - 如何从命令行覆盖 protractor.conf.js 值?

angularjs - 以 Angular 管理相关对象的最佳方法?