2015-06-10 150 views
0

我是新的AngularJS。我试图用单个复选框选中所有复选框,并执行checkboxClick方法。因为我们将值设定为范围。怎么做?选择angularJS中的所有复选框

<input class="check-box" data-val="true" type="checkbox">Select All </input> 
      <table class="table table-bordered"> 
        <tr> 
         <th></th> 
         <th>Printed</th> 
         <th>First Name</th> 
         <th>Last Name</th> 
         <th>Company</th> 
         <th>City</th> 
         <th>Country</th> 
        </tr> 
        <tr ng-repeat="item in items"> 
         <td> 
          <input class="check-box" data-val="true" type="checkbox" ng-model="item.selected" ng-click="checkboxClick($event, item)"> 
          </td> 
          <td> 
          {{item.printed}} 
          </td> 
          .... 
          .... 
         </tr> 
        </table> 

JS

$scope.checkboxClick = function (eventobj, item) { 
     if (eventobj.target.checked) { 
      $scope.selectedItems.push(item); 
      $scope.getLabel(item.id); 
      $scope.getOrderItems(item.id); 
      $scope.getPaymentItems(item.id); 
     } else { 
      $scope.removeItemFromSelection(item); 
     }; 
    }; 
+0

您或许对这个[的jsfiddle(http://jsfiddle.net/deeptechtons/TKVH6/)。 – arman1991

回答

2

你想要的功能这是通过复选框上的ng-click事件启动的。这也将取消选中所有复选框。它迭代所有项目,改变每个项目的状态。

<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" /> 
    <tr ng-repeat="item in items"> 
     <td> 
      {{item.name}} 
     </td> 
     <td> 
      <input type="checkbox" ng-model="item.Selected" /> 
     </td> 
    </tr> 

控制器可以是这个样子:

angular.module("myApp", []) 
    .controller("checkboxCtrl", function($scope) { 

    $scope.Items = [{ 
     name: "one" 
    }, { 
     name: "two" 
    }, { 
     name: "three" 
    }]; 

    $scope.checkAll = function() { 
     angular.forEach($scope.Items, function (item) { 
      item.Selected = $scope.selectAll; 
     }); 
    }; 
}); 
+0

选择全部并取消选择所有工作正常。但是'ng-click'函数在选中或取消选中时不会触发项目 – James123

+0

@ James123您确定您已将控制器添加到正确的位置。如果输入在控制器之外,则它将不起作用,因为它没有该功能。这是一个[工作示例](http://jsfiddle.net/xcxf7p1y/)。 –

1

你可以在你的HTML一个简单的变量做到这一点:

<input class="check-box" data-val="true" type="checkbox" ng-model="item.selected" ng-click="checkboxClick($event, item)" ng-selected="checkAll"> 
<button ng-click="toggleAllCheckboxes()">Check/Uncheck All</button> 

,并在你的控制器:

$scope.checkAll = false; 
$scope.toggleAllCheckboxes = function(){ 
    $scope.checkAll = !$scope.checkAll; 
} 
+0

我不是在寻找按钮。 ' James123