【问题标题】:How to check all children based on parent while also checking parent based on children?如何根据父母检查所有孩子,同时根据孩子检查父母?
【发布时间】:2016-05-13 22:39:15
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs checkbox ng-repeat angularjs-ng-checked


    【解决方案1】:

    你可以试试。更改continent 值时调用function

    <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 DEMO LINK

    【讨论】:

      【解决方案2】:

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

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

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

      Here is the example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-29
        • 2023-02-06
        • 1970-01-01
        • 1970-01-01
        • 2017-12-28
        相关资源
        最近更新 更多