6

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

为了做到这一点,我使用了这个 SO answer中描述的第一种方法。虽然从列表中正确添加和删除了值,但当我单击它们时,这些框不再显示为“选中”。我的代码在下面,我也在这个 codepen中重新创建了问题。

我的复选框的 HTML

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

来自控制器的 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);
    }
  };
});
4

1 回答 1

4

尝试改变这个:

ng-checked="selection.indexOf(site) > -1" 

对此:

ng-checked="{{selection.indexOf(site) > -1}}" 

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

于 2015-04-06T01:15:53.893 回答