加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何根据angular.js中的子复选框选择父复选框?

发布时间:2020-12-17 17:40:05 所属栏目:安全 来源:网络整理
导读:我最近一直在玩Angular.js并决定在选中父复选框后检查所有复选框,我已经使用ng-model和ng-checked指令完成了. div ng-app div ng-controller="Ctrl" input type="checkbox" ng-model="parent"/ Select Allbr/ input type="checkbox" ng-model="child_1" ng-c
我最近一直在玩Angular.js并决定在选中父复选框后检查所有复选框,我已经使用ng-model和ng-checked指令完成了.

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

现在,我正在尝试选中所有子复选框,一旦检查了所有子复选框但面临一些问题.

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/codef0rmer/QekpX/

我们可以使上面的代码更健壮吗?

解决方法

复选框中的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 example in jsfiddle

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读