【问题标题】:How to check/uncheck all other checkboxes using one checkbox in angularjs?如何使用angularjs中的一个复选框选中/取消选中所有其他复选框?
【发布时间】:2015-11-17 17:44:00
【问题描述】:

$scope.checkAll = function() {
  if ($scope.selectedAll) {
    $scope.selectedAll = true;
  } else {
    $scope.selectedAll = false;
  }

  angular.forEach($scope.MyProducts, function(item) {
    item.Selected = $scope.selectedAll;
  });
  /*});*/
}
<div class="panel-heading col-xs-12">
  <h6 class="viewStyle col-xs-4"><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />Select All</h6>
</div>

<div id="gridView" ng-repeat="product in MyProducts">

  <input style="float:left" type="checkbox" ng-model="product.Selected" ng-checked="product.Selected" value="product.ProductId" />

</div>

由于我正在使用两个 div,因为我试图使用一个复选框来自动检查所有其他复选框,但我无法这样做,所以我共享了 html 和我的控制器代码,请帮忙。

【问题讨论】:

标签: javascript css angularjs html


【解决方案1】:

这是一个如何做到这一点的例子。你不需要ng-checkedng-model 足以实现你想要的。

angular.module("myApp", []).controller("myCtrl", function($scope) {
  $scope.myProducts = [{
    selected: false,
    productId: 1,
    name: "CheckBox1"
  }, {
    selected: false,
    productId: 2,
    name: "CheckBox2"
  }];
  $scope.selectedAll = false;
  $scope.checkAll = function() {
    $scope.myProducts.forEach(function(product) {
      product.selected = !$scope.selectedAll;
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div class="panel-heading col-xs-12">
    <h6 class="viewStyle col-xs-4"><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />Select All</h6>
  </div>

  <div id="gridView" ng-repeat="product in myProducts">

    <input type="checkbox" ng-model="product.selected" value="product.productId">{{product.name}}</input>

  </div>
</div>

【讨论】:

    【解决方案2】:

    您可以使用ng-change 代替ng-click 来更改复选框值。

    在 HTML 中:

    <div ng-app="myApp" ng-controller="myCtrl">
      <div class="panel-heading col-xs-12">
        <h6 class="viewStyle col-xs-4"><input type="checkbox" ng-model="selectedAll" ng-change="checkAll()" />Select All</h6>
      </div>
    
      <div id="gridView" ng-repeat="product in myProducts">
    
        <input type="checkbox" ng-model="product.selected" value="product.productId">{{product.name}}</input>
    
      </div>
    </div>
    

    在控制器中:

    $scope.checkAll = function() {
       angular.forEach($scope.myProducts, function(product) {
             product.selected = $scope.selectedAll;
       });
     };
    

    Working PLUNKER code

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 2017-01-03
      • 2023-04-05
      • 2023-03-19
      相关资源
      最近更新 更多