选择angularJS中的所有复选框

select all checkboxes in angularJS

本文关键字:复选框 angularJS 选择      更新时间:2023-09-26

我是新的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);
        };
    };

您希望使用复选框上的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;
        });
    };   
});

您可以在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;
}