用到了ng-model和ng-change,和ng-repeat,vm就是如此便利。
簡單樹效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<label>
<input type="checkbox" ng-model="select_all" ng-change="selectAll(select_all)">
</label>
<ul>
<li ng-repeat="i in list">
<input type="checkbox" ng-model="i.$checked" ng-change="selectOne(i)"> <span>{{i.id}}</span>
<ul>
<li ng-repeat="it in i.child">
<input type="checkbox" ng-model="it.$checked" ng-change="selectOneIn(i)"> <span>{{it.id}}</span> </li>
</ul>
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', function($scope) {
$scope.list = [{
'id': 101,
'child': [{
'id': 1010,
'flag': false
}, {
'id': 1001,
'flag': false
}]
}, {
'id': 201,
'child': [{
'id': 2010,
'flag': false
}, {
'id': 2001,
'flag': false
}]
}];
$scope.selectAll = function(i) {
if (i) {
angular.forEach($scope.list, function(v) {
v.$checked = true;
angular.forEach(v.child, function(k) {
k.$checked = true;
});
})
} else {
angular.forEach($scope.list, function(v) {
v.$checked = false;
angular.forEach(v.child, function(k) {
k.$checked = false;
});
})
}
};
$scope.selectOne = function(i) {
if (i.$checked) {
angular.forEach(i.child, function(v) {
v.$checked = true;
});
} else {
angular.forEach(i.child, function(v) {
v.$checked = false;
});
}
checkItem();
};
$scope.selectOneIn = function(i) {
var _bf = 0;
var _bt = 0;
angular.forEach(i.child, function(iChild) {
if (iChild.$checked) {
_bt++;
} else {
_bf++;
}
})
if (_bf == i.child.length) {
i.$checked = false;
}
if (_bt > 0) {
i.$checked = true;
}
checkItem();
}
function checkItem(){
var _t = 0;
angular.forEach($scope.list, function(v) {
if (v.$checked) {
_t++;
}
});
if (_t > 0) {
$scope.select_all = true;
} else {
$scope.select_all = false;
}
}
}]);
</script>
</body>
</html>