如何根据angular.js子复选框选中复选框父母? [英] How to select parent checkbox based on child checkboxes in angular.js?

查看:150
本文介绍了如何根据angular.js子复选框选中复选框父母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩Angular.js最近并决定检查所有的复选框,一旦父复选框被选中,我已经使用 NG-模型和完成 NG-检查指令。

I've been playing with Angular.js recently and decided to check all the checkboxes once parent checkbox is checked, which I've done using ng-model and ng-checked directives.

    <div ng-app>
        <div ng-controller="Ctrl">
            <input type="checkbox" ng-model="parent"/> Select All<br/>
            <input type="checkbox" ng-model="child_1" ng-checked="parent" ng-click="getAllSelected()"/> First<br/>
            <input type="checkbox" ng-model="child_2" ng-checked="parent" ng-click="getAllSelected()"/> Second<br/>
            <input type="checkbox" ng-model="child_3" ng-checked="parent" ng-click="getAllSelected()"/> Three<br/>
            <input type="checkbox" ng-model="child_4" ng-checked="parent" ng-click="getAllSelected()"/> Four<br/>
            <input type="checkbox" ng-model="child_5" ng-checked="parent" ng-click="getAllSelected()"/> Five<br/>
        </div>
    </div>

现在我想选择所有的复选框家长一旦所有的孩子复选框被选中,但面临着一些问题。

Now I'm trying select all the parent checkbox once all the child checkboxes are checked but facing some issues.

    function Ctrl($scope) {
       $scope.getAllSelected = function () {
          var chkChild = document.querySelectorAll('input[ng-model^="child_"]').length;
          var chkChildChecked = document.querySelectorAll('input[ng-model^="child_"]:checked').length;
          if (chkChild === chkChildChecked) $scope.parent= true;
          else $scope.parent= false;
       }
    }

演示: http://jsfiddle.net/$c$cf0rmer/QekpX/

我们能作出上述code更强大的?

Can we make the above code more robust?

推荐答案

在复选框的NG-checked属性发生在一个前pression。所以,你可以给一个前pression与和/或条件,如下所述,使其托运基于一个前pression。

The ng-checked attribute in the checkbox takes in an expression. So you can give an expression with and/or conditions, as mentioned below to make it checked based on an expression.

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

您不必须写一个函数seprate做计算点击每个孩子复选框之后。

You dont have to write a seprate function to do the computation when every child checkbox is clicked.

下面是例子的jsfiddle

这篇关于如何根据angular.js子复选框选中复选框父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆