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>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值