将Angular Material Design复选框绑定到Controller中的数组

dsa*_*951 5 javascript angularjs angular-material

我有一组材料设计复选框,我想将它们的值绑定到我的控制器中的数组.

为了实现这一点,我使用了本SO答案中描述的第一种方法.正确地在列表中添加和删除值时,单击它们时,框不再显示为"已选中".我的代码在下面,我也在这个codepen中重新创建了问题.

我的复选框的HTML

<md-checkbox 
    ng-repeat="site in websites" 
    value="{{site}}" 
    ng-checked="selection.indexOf(site) > -1" 
    ng-click="toggleSelection(site)"> 
    {{site}}
</md-checkbox>
Run Code Online (Sandbox Code Playgroud)

来自Controller的JavaScript

  $scope.websites = ['Facebook', 'Twitter', 'Amazon'];
  $scope.selection = ['Facebook'];
  $scope.toggleSelection = function toggleSelection(site) {
    var idx = $scope.selection.indexOf(site);

    // is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // is newly selected
    else {
      $scope.selection.push(site);
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

jar*_*arz 4

尝试改变这个:

ng-checked="selection.indexOf(site) > -1" 
Run Code Online (Sandbox Code Playgroud)

对此:

ng-checked="{{selection.indexOf(site) > -1}}" 
Run Code Online (Sandbox Code Playgroud)

为我工作: http: //codepen.io/anon/pen/xbNOmE