Angular Checkboxes “Select All” functionality with only one box selected initially

前端 未结 3 2079
庸人自扰
庸人自扰 2020-12-02 15:48

I have a form that contains 3 checkboxes: \"Select All\", \"Option 1\", and \"Option 2\".

相关标签:
3条回答
  • 2020-12-02 16:14

    Another way to go about it is to use a model for the options, set default selection in the model and have your controller handle the logic of doing select all.

    angular.module("app", []).controller("ctrl", function($scope){
      
      $scope.options = [
        {value:'Option1', selected:true}, 
        {value:'Option2', selected:false}
      ];
      
      $scope.toggleAll = function() {
         var toggleStatus = !$scope.isAllSelected;
         angular.forEach($scope.options, function(itm){ itm.selected = toggleStatus; });
       
      }
      
      $scope.optionToggled = function(){
        $scope.isAllSelected = $scope.options.every(function(itm){ return itm.selected; })
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">    </script>
    <div ng-app="app" ng-controller="ctrl">
    <form id="selectionForm">
        <input type="checkbox" ng-click="toggleAll()" ng-model="isAllSelected">Select all
        <br>
         <div ng-repeat = "option in options">
            <input type="checkbox" ng-model="option.selected" ng-change="optionToggled()">{{option.value}}
         </div>
    </form>
      {{options}} 
    </div>

    0 讨论(0)
  • 2020-12-02 16:22

    I like to use an ng-repeat for clarity on showing what you're selecting/un-selecting, basically you end up with a nice little object to base it all on, and adding to it is just easier.

    Here's a Plunker

    *Also notice how you can achieve allSelected? with a loop func and not a ton of html, and I'm sure this can be done with less spaghetti but it works *

    app.controller('MainCtrl', function($scope) {
    
    $scope.allSelected = false;
    
    $scope.checkboxes = [{label: 'Option 1',checked: true}, {label: 'Option 2'}}}];
    
    $scope.cbChecked = function(){
      $scope.allSelected = true;
      angular.forEach($scope.checkboxes, function(v, k) {
        if(!v.checked){
          $scope.allSelected = false;
        }
      });
    }
    $scope.toggleAll = function() {
        var bool = true;
        if ($scope.allSelected) {
          bool = false;
        }
        angular.forEach($scope.checkboxes, function(v, k) {
          v.checked = !bool;
          $scope.allSelected = !bool;
          });
       }
    });
    
    0 讨论(0)
  • 2020-12-02 16:31

    Try this:

    <form id="selectionForm">
        <input type="checkbox" ng-model="selectAll" >Select all
        <br>
        <input type="checkbox" ng-checked="selectAll || option1" ng-init="option1=true" ng-model="option1">Option 1
        <br>
        <input type="checkbox" ng-checked="selectAll">Option 2
    </form>
    
    0 讨论(0)
提交回复
热议问题