angularJS关于checkbox复选框多选全选与反选
[ 2017/07/20, AngularJS , 4224阅, 0评 ]

angularjs_checkbox.gif

直接上代码了,html如下:

<dd ng-repeat="x in testCheckData">
    <input type="checkbox" ng-checked="isChecked(x.id)" ng-click="updateMyCheck($event,x.id)">{{x.name}}
</dd>
<dt>已选:{{choosedId}}</dt>
<input type="button" ng-click="chooseAll()" value="全选">
<input type="button" ng-click="chooseBack()" value="反选">

核心js如下:

$scope.testCheckData = [
	{id:1,name:"第1个"},
	{id:2,name:"第2个"},
	{id:3,name:"第3个"},
	{id:4,name:"第4个"},
	{id:5,name:"第5个"},
];
$scope.choosedId = [];
$scope.isChecked = function(id){  
	return $scope.choosedId.indexOf(id) != -1;  
};
$scope.updateMyCheck = function($event,id){
	if($event.target.checked){
		$scope.choosedId.push(id);
	}else{
		$scope.choosedId.splice($scope.choosedId.indexOf(id), 1);
	}
};
//全选
$scope.chooseAll = function(){
	$scope.choosedId = [];
	for(i=0;i<$scope.testCheckData.length;i++){
		$scope.choosedId.push($scope.testCheckData[i].id);
	}
};
//反选
$scope.chooseBack = function(){
	if($scope.choosedId.length==0){
		$scope.chooseAll();
	}else if($scope.choosedId.length==$scope.testCheckData.length){
		$scope.choosedId = [];
	}else{
		for(i=0;i<$scope.testCheckData.length;i++){
			if($scope.choosedId.indexOf($scope.testCheckData[i].id) != -1){
				$scope.choosedId.splice($scope.choosedId.indexOf($scope.testCheckData[i].id), 1);
			}else{
				$scope.choosedId.push($scope.testCheckData[i].id);
			}
		}
	}
};

有朋自远方来...评论一下呗O(∩_∩)O