无法在使用Angular的复选框上执行selectall

时间:2015-07-23 18:02:18

标签: javascript html angularjs

我似乎无法弄清楚如何选择另一个复选框并取消选择所有框。

JSFIDDLE

   <div ng-controller="tempCtrl">
    <input type="checkbox" ng-model="selectAllOptions" ng-click="selectAll()" /> Select/Deselect All
    <li ng-repeat="t in parameters.myMainOptions.teams">
        <input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
    <button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
        {{form.selectedTeams}}
    </pre>

</div>

var myApp = angular.module('myApp', []);

myApp.controller("tempCtrl", function ($scope) {
    $scope.form = {
        selectedTeams: {}
    };
    $scope.parameters = {
        myMainOptions: {
            teams: ['angels', 'giants', 'orioles', 'bluejays', 'athletics']
        }
    };

    $scope.selectAll = function() {
         //This is where I'm stuck   
    }
});

3 个答案:

答案 0 :(得分:1)

这是一个简单的选择/取消选择所有复选框的工作插件:

plunkr

<强>控制器

*_

查看

$scope.checkboxes = [
    {
      selected: false
    },
    {
      selected: false
    },
    {
      selected: false
    }
  ];

  // Check/uncheck all boxes
  $scope.checkAll = function () {
    angular.forEach($scope.checkboxes, function (obj) {
      obj.selected = $scope.selectAll;
    });
  };

答案 1 :(得分:0)

您可以在forEach数组上执行$scope.parameters.myMainOptions.teams,然后在循环中设置$scope.form.selectedTeams值。也可以使用ng-change代替ng-click

<强>标记

<input type="checkbox" ng-model="selectAllOptions" ng-change="selectAll()" />Select/Deselect All
<li ng-repeat="t in parameters.myMainOptions.teams">
    <input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
<button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
    {{form.selectedTeams}}
</pre>

<强>代码

$scope.selectAll = function () {
    angular.forEach($scope.parameters.myMainOptions.teams, function (value, index) {
        $scope.form.selectedTeams[value] = $scope.selectAllOptions; //setting selectAll variable value
    })
}

Working Fiddle

答案 2 :(得分:0)

首先,你应该让团队成为像这样的对象数组

<强>控制器:

   $scope.parameters = {
        myMainOptions: {
          teams: [{name: 'angels'}, {name: 'giants'}, {name: 'orioles'}, {name:'bluejays'}, {name: 'athletics'}]  
        }
    };

这是一种更好的方法,因为现在您可以为每个团队对象添加一个选定的属性。

然后你应该将每个团队的ng-model复选框设置为team.selected,如下所示:

查看:

<li ng-repeat="team in parameters.myMainOptions.teams">
        <input ng-model="team.selected" type="checkbox" />
        {{team}}
</li>

现在,如果您选中天使复选框,则该对象将更改为{name: 'angels', selected: true}

然后你的selectAll函数将如下所示:

<强>控制器:

   $scope.selectAll = function () {
        angular.forEach($scope.parameters.myMainOptions.teams, function (team) {
           team.selected = $scope.selectAllOptions;
        });
      };