0

Plnkr:https ://plnkr.co/edit/Tt96EE2rruy1HAudRVJR?p=preview

我有以下嵌套的复选框循环:

<ul>
  <li ng-repeat="continent in destinations">
    <input type="checkbox" ng-model="continent.selected">
    {{continent.name}} ({{continent.countries_selected}} / {{continent.countries.length}}) - {{continent.all_selected}}
    <ul>
      <li ng-repeat="country in continent.countries">
        <input type="checkbox" ng-model="country.selected" ng-checked="continent.selected">
        {{country.name}}
      </li>
    </ul>
  </li>
</ul>

这是检测 ($watch) 是否已选中部分或所有子复选框的代码,如果是,则父复选框也会被选中。

这很好用。

但是,当我检查父框时,它不会检查。

我想要实现的是,当我选中父复选框时,它的所有子复选框也会被选中,当我取消选中父复选框时,它的所有子复选框都会被选中。

$scope.$watch('destinations', function(destinations){

  var total_selected = 0;

  angular.forEach(destinations, function(continent){

    continent.countries_selected = 0;

    angular.forEach(continent.countries, function(country){

      total_selected += country.selected ? 1 : 0

      continent.countries_selected += country.selected ? 1 : 0

      if (continent.countries_selected == continent.countries.length) {
        continent.selected = true;
      } else {
        continent.selected = false;
      }

    });

  });

  $scope.select_all = function(continent){
    continent.selected = true;
  }

  $scope.total_selected = total_selected;

}, true);
4

2 回答 2

0

你可以试试 。调用价值function变化continent

<input type="checkbox" ng-model="continent.selected" ng-change="parentChange($index)">

并在控制器中:添加另一个功能

$scope.parentChange = function(index) {
    angular.forEach( $scope.destinations[index].countries, function(country) {
      country.selected = $scope.destinations[index].selected;
    });
  };

并且可能不需要添加ng-checked="continent.selected"国家复选框。

利用

<input type="checkbox" ng-model="country.selected">

代替

<input type="checkbox" ng-model="country.selected" ng-checked="continent.selected">

Plunker 演示链接

于 2016-02-04T11:09:08.080 回答
0

复选框中的 ng-checked 属性接受一个表达式。因此,您可以给出一个带有和/或条件的表达式,如下所述,以使其基于表达式进行检查。

<input type="checkbox" ng-checked="child_1 && child_2 && child_3 && child_4 && child_5" ng-model="parent"/> Select All<br/>

单击每个子复选框时,您不必编写单独的函数来进行计算

这是示例

于 2016-04-20T18:36:10.370 回答