本文的angular使用的1.6.1的版本,结合bootstrap的完善全选的功能
HTML:
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<title>自己写的</title>
</head>
<link href="bootstrap.css" rel="stylesheet">
<script src="angular.js"></script>
<body ng-controller='myController'>
<div ng-repeat='item in list' style='padding-left: 50px;border-bottom:1px solid red'>
<div class="checkbox" >
<input id="checkbox2-{{item.id}}" type="checkbox"
hb-select-all='item.rules' ng-checked='isAllChecked' select-key='is_select' select-true-value='1' select-false-value='0' select-value-type='number'>
<label for="checkbox2-{{item.id}}" >全选 {{item.name}}</label>
</div>
<div class="form-group col-sm-12" ng-repeat = 'rulelist in item.rules' >
<div class="checkbox">
<input id={{rulelist.id}} type="checkbox" ng-model="rulelist.is_select"
ng-true-value="1" ng-false-value="0" >
<label class="control-label text-center col-sm-2" for={{rulelist.id}}>name:</label>
</div>
<div>{{rulelist.name}}</div>
</div>
</div>
</body>
</html>
解释:先定义ng-app 其次是controller名字的 一个全选的按钮,剩下的就是checkbox通过ng-reapeat来实现的
<input id="checkbox2-{{item.id}}" type="checkbox" hb-select-all='item.rules' ng-checked='isAllChecked' select-key='is_select' select-true-value='1' select-false-value='0' select-value-type='number'>
这上面的就是指令
JS:
<script type="text/javascript">
angular.module('myApp',[]) //入口
.controller('myController', ['$scope', function ($scope) { //注意方括号的写法
$scope.list = [ //自己写的假数据 方便ng-reapeat 定义规则:is_select =>0 : 未选中
{ //is_select =>1 选中
name:'张沪生',
id:12,
rules:[
{
id:1,
is_select:0,
name:'小沪生'
},
{
id:2,
is_select:1,
name:'大沪生'
},
{
id:14,
is_select:0,
name:'沪生'
}
]
}
]
}])
//hbSelectAll => html上面的hb-select-all='item.rules'
.directive('hbSelectAll', ['$rootScope', '$timeout','$compile',function($rootScope, $timeout,$compile) {
return {
restrict: 'AE',
scope: true,
controller: ['$scope','$element','$attrs',function ($scope, $element,$attrs) {
console.info($attrs); //打印出来看看图一
console.info($element) //全选的标签的按钮
//初始化的默认值
var selectKey=$attrs.selectKey||'is_select';
var selectTrueValue=$attrs.selectTrueValue||true;
var selectFalseValue=$attrs.selectFalseValue||false;
var selectValueType=$attrs.selectValueType||'number';
var newArr = [];
$scope.$watch($attrs.hbSelectAll,function(newVal,oldVal){
console.info('newVal',newVal,'oldVal',oldVal) //自己观察的新、旧值得变化
$scope.isAllChecked = newVal.every(n=>{
//console.info(n[selectKey])
return n[selectKey] == selectTrueValue //every的条件 返回的true or false
});
//console.info($scope.isAllChecked)
newArr = newVal;
//console.info('newArr',newArr)
},true)
$element.on('change',function () {
if($scope.isAllChecked){ //true
$scope.$apply(function () {
newArr.forEach(n=>{
n[selectKey]=selectFalseValue //change false
})
})
}else{ // false
$scope.$apply(function () {
newArr.forEach(n=>{
n[selectKey]=selectTrueValue //change true
})
})
}
})
}]
};
}])
</script>
这就是$attrs的打印出来的值(图一)