AngularJS实现复选框全选功能

实现要点:

ng-checked:该属性影响复选框的状态,值为true则复选框选中,值为false则取消选中。

需要注意的是复选框的状态不会影响该属性的值,必须在复选框的单击事件中同步选框状态与该属性值。

页面如下

<!DOCTYPE html>
<html ng-app="myModule">
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <script src="js/angular.js"></script>
</head>
<body>

  <div ng-controller="myCtrl">
    <input type="checkbox" ng-checked="isAllSelect" ng-click="selectAll($event)"/>全选<br />
    <br />
    <p ng-repeat="entity in list">
    	<input type="checkbox" ng-checked="isSelect" ng-click="updateSelection($event,entity.id)"/>{{entity.id}}:{{entity.text}}
    </p>
 		<p>你选择的工具是:{{selectIds}}</p>
  </div>

<script>
  var app = angular.module('myModule',['ng']);

  app.controller('myCtrl', function ($scope) {
  		//声明集合
  		$scope.list=[{id:1,text:'汽车'},{id:2,text:'飞机'},{id:3,text:'火车'}];
  		$scope.selectIds=[];//用户勾选的集合id
			//单个复选框
			$scope.updateSelection=function($event,id){
				if($event.target.checked){//如果是被选中,则增加到数组
						$scope.selectIds.push(id);
						if($scope.selectIds.length == $scope.list.length){
							$scope.isAllSelect=true;
							$scope.isSelect=true;
						}
				}else{
						var idx = $scope.selectIds.indexOf(id);
		        $scope.selectIds.splice(idx, 1);//删除 
		        $scope.isAllSelect=false;
		        if($scope.selectIds.length==0){
		        	$scope.isSelect=false;
		        }
				}
			}
  	$scope.selectAll=function($event){

			if($event.target.checked){
				//如果是被选中,则增加全部id到数组
				$scope.selectIds=[];
				$scope.isAllSelect=true;
				$scope.isSelect=true;			
		    angular.forEach($scope.list, function (value,key) {
		    	  $scope.selectIds.push(value.id);
		        });
			}else{
				$scope.isAllSelect=false;
				$scope.isSelect=false;
				$scope.selectIds=[];
			}
  	}
  	
  })
</script>

</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章