我怎样才能使用"全选"复选框传递所有对象?

时间:2018-01-18 16:10:45

标签: javascript angularjs

我创建了一个用户可以选择/取消选择员工的页面。我使用.push将这些员工添加到数组users。我有单个用户的复选框和一个选中/取消选择所有用户的复选框。检查和取消选中个人用户是否有效,但我仍坚持使用"全选"复选框。

这是HTML:

<div ng-app="myApp">
  <div ng-controller="MainCtrl">

    <label>Select All</label><br>
    <input type="checkbox" ng-model="all" ng-change="addremoveall(all, user.ID)">
    <table>
      <tr>
        <th></th>
        <th>User</th>
        <th>First Name</th>
        <th>Last Name</th>
      </tr>
      <tr ng-repeat="user in users">
        <td><input type="checkbox" ng-model="checked" ng-change="addremoveuser(checked, user.ID)"></td>
        <td>{{user.Title}}</td>
        <td>{{user.FirstName}}</td>
        <td>{{user.LastName}}</td>
      </tr>
    </table>
  </div>
</div>

这是JS:

var app = angular.module('myApp', ['ngSanitize']);
app.controller('MainCtrl', function($scope, $http, $q){
    var users = [];
    $scope.addremoveuser = function (checked, id) {
        if (checked) {
            console.log("user selected", id);
            users.push(id)
            console.log("if test", users);
        }
        else {
            console.log("user unselected", id);
            var index = users.indexOf(id);
            users.splice(index);
            console.log("else test", users);
        }
    };
    $scope.addremoveall = function (all, id) {
            if (all) {
                console.log("all selected", id);
                users.push(id)
                console.log("if test", users);
            }
            else {
                console.log("all unselected", id);
                var index = users.indexOf(id);
                users.splice(index);
                console.log("else test", users);
            }
    };

});

1 个答案:

答案 0 :(得分:1)

您必须将每个复选框与关联用户绑定。

尝试类似

的内容
<div ng-app="myApp">
    <div ng-controller="MainCtrl">
    <label>Select All</label><br>
    <input type="checkbox" ng-model="globalChecked" ng-change="addremoveall()">
    <table>
      <tr>
        <th></th>
        <th>User</th>
        <th>First Name</th>
        <th>Last Name</th>
      </tr>
      <tr ng-repeat="user in users">
        <td><input type="checkbox" ng-model="user.checked" ng-change="addremoveuser(user)"></td>
        <td>{{user.Title}}</td>
        <td>{{user.FirstName}}</td>
        <td>{{user.LastName}}</td>
      </tr>
    </table>
  </div>
</div>

$scope.globalChecked = false;

$scope.addremoveuser = function (user) {
    if (user.checked) {
        $scope.users.push(user);
    } else {
        $scope.user.splice(user, 1);
    }
}

$scope.addremoveall = function () {
    for (let i in $scope.users) {
        $scope.users[i].checked = $scope.globalChecked;
    }
}