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>

 

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