选择angularJS中的所有复选框

时间:2015-06-10 21:19:50

标签: javascript angularjs checkbox

我是新的AngularJS。我正在尝试使用单个复选框选中所有复选框,并执行checkboxClick方法。因为我们将值设置为范围。怎么做?

<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);
        };
    };

2 个答案:

答案 0 :(得分: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;
        });
    };   
});

答案 1 :(得分: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;
}