当我没有任何记录时,默认选中所有复选框

时间:2017-10-05 15:14:31

标签: javascript angularjs

当没有记录时,我通过选中所有按钮来解决问题。

以下是我的代码:

<input type="checkbox" ng-model="selectAll" ng-model-options="{getterSetter: true}"/>

 var getAllSelected= function () {
        var selectedItems = $scope.items.filter(function (item) {
            return item.selected;
        });
        return selectedItems.length === $scope.items.length;
    }

    var setAllSelected = function (value) {
        angular.forEach($scope.items, function (item) {
            item.selected = value;
        });
    }

    $scope.selectAll = function (value) {
        if (value !== undefined) {
            return setAllSelected(value);
        } else {
            return getAllSelected();
        }
    }

因此,如果我的$scope.items中没有记录,问题就出现了:

return selectedItems.length === $scope.items.length;

2 个答案:

答案 0 :(得分:1)

非常简单的修复,只需添加条件以确保长度不为零。

return $scope.items.length != 0 && selectedItems.length === $scope.items.length;

答案 1 :(得分:1)

我已使用以下代码段尝试了您的代码:

var app = angular.module('app', [])

.controller('ctrl', ['$scope', function($scope) {


$scope.value = false;
$scope.items = [{},{}];

 var getAllSelected= function () {
        var selectedItems = $scope.items.filter(function (item) {
            return item.selected;
        });
        return $scope.items.length != 0 && selectedItems.length === $scope.items.length;
    }

    var setAllSelected = function (value) {
      console.log(value);
        angular.forEach($scope.items, function (item) {
            item.selected = value;
        });
    }

    $scope.selectAll = function (value) {
      console.log(value);
        if (value !== undefined) {
            return setAllSelected(value);
        } else {
            return getAllSelected();
        }
    }
  }]);

  <input type="checkbox" ng-model="selectAll" ng-model-options="{getterSetter: true}"/>

它工作正常..

您可以在此处查看:https://plnkr.co/edit/oUjNQGI363SJPMeaWA6A?p=preview