栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何获取带有选择/取消选择所有功能和不确定值的angular.js复选框?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何获取带有选择/取消选择所有功能和不确定值的angular.js复选框?

由于您需要一种新的类型/类型的组件,因此这对于自定义指令来说是一个很好的案例。
由于父/主/三态复选框和各个双状态复选框需要相互交互,因此我建议使用带有其自己的控制器的单个指令来处理逻辑。

<tri-state-checkbox checkboxes="listelements"></tri-state-checkbox>

指示:

app.directive('triStateCheckbox', function() {  return {    replace: true,    restrict: 'E',    scope: { checkboxes: '=' },    template: '<div><input type="checkbox" ng-model="master" ng-change="masterChange()">'      + '<div ng-repeat="cb in checkboxes">'      + '<input type="checkbox" ng-model="cb.isSelected" ng-change="cbChange()">{{cb.desc}}'      + '</div>'      + '</div>',    controller: function($scope, $element) {      $scope.masterChange = function() {        if($scope.master) {          angular.forEach($scope.checkboxes, function(cb, index){ cb.isSelected = true;          });        } else {          angular.forEach($scope.checkboxes, function(cb, index){ cb.isSelected = false;          });        }      };      var masterCb = $element.children()[0];      $scope.cbChange = function() {        var allSet = true, allClear = true;        angular.forEach($scope.checkboxes, function(cb, index){          if(cb.isSelected) { allClear = false;          } else { allSet = false;          }        });        if(allSet)        {$scope.master = true;masterCb.indeterminate = false;        }        else if(allClear) {$scope.master = false;masterCb.indeterminate = false;        }        else {$scope.master = false;          masterCb.indeterminate = true;        }      };      $scope.cbChange();  // initialize    },  };});

更改模板以满足您的需要,或者将外部模板与templateUrl一起使用。

该指令假定checkboxes数组包含具有

isSelected
属性和
desc
属性的对象。

柱塞。

更新
:如果您只希望该指令仅呈现三态复选框,因此单个复选框位于HTML中(例如@Piran的解决方案),这是该方法的另一个更小巧的变体。对于这个笨拙的人,HTML将是:

<tri-state-checkbox checkboxes="listelements" ></tri-state-checkbox>select all<div ng-repeat="item in listelements">   <input type="checkbox" ng-model="item.isSelected"> {{item.desc}}</div>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636254.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号