1. 程式人生 > >checkbox解決全選反選的問題

checkbox解決全選反選的問題

實現需求:

1.all的checkbox可全部選中或全部取消

2.小的checkbox全部選中時,all的checkbox自動選中

3.全部選中後,取消小的checkbox,all的checkbox自動取消

<!doctype html>  
<html ng-app='myApp' ng-controller="myCtrl">   
<head>     
</head>   
<body>       
 <div>
  <label for="flag">全選
    <input type="checkbox" ng-model="all" ng-checked="select_all" ng-click="selectAll()">{{select_all}}
  </label>
  <ul>
    <li ng-repeat="i in list">
      <input type="checkbox" ng-model="i.id" ng-checked="i.checked" ng-click="selectOne(i)">
      <span>{{i.id}}{{i.checked}}</span>
    </li>
  </ul>
</div>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>  
<script type="text/javascript">      
  var myApp=angular.module('myApp',[]); 
  myApp.controller('myCtrl',function($scope){
    $scope.select_all = false
    $scope.list = [
    {id: 1,value:11,checked:false},
    {id: 2,value:22,checked:false},
    {id: 3,value:33,checked:false},
    {id: 4,value:44,checked:false},
    {id: 5,value:55,checked:false},
    {id: 6,value:66,checked:false},
    {id: 7,value:77,checked:false}
    ];
    $scope.checked = [];
    $scope.selectAll = function () {
      $scope.select_all = !$scope.select_all;
      if($scope.select_all) {
        $scope.checked = [];
        angular.forEach($scope.list, function (i) {
          i.checked = true;
          $scope.checked.push(i.id);
        })
      }else {
        angular.forEach($scope.list, function (i) {
          i.checked = false;
          $scope.checked = [];
        })
      }
    };
    $scope.selectOne = function (i) {
      i.checked = !i.checked;
      angular.forEach($scope.list , function (i) {
        var index = $scope.checked.indexOf(i.id);
        if(i.checked && index === -1) {
          $scope.checked.push(i.id);
        } else if (!i.checked && index !== -1){
          $scope.checked.splice(index, 1);
        };
      })

      if ($scope.list.length === $scope.checked.length) {
        $scope.select_all = true;
      } else {
        $scope.select_all = false;
      }
    }
  })
</script>  
</body></html>