如何根据AngularJS中的复选框选择和动态过滤在Array中添加或删除值列表?

时间:2015-07-29 03:41:13

标签: javascript angularjs checkbox

$scope.selectObjectType = function () {
    $scope.selected = []; // clear previous state
     $scope.model.allItemsSelected = true; // all are selected unless...
     // If any object type is not checked, then uncheck the "allItemsSelected" checkbox
    for (var i = 0; i < $scope.model.objectTypes.length; i++) {
        if (!$scope.model.objectTypes[i].isChecked) { 
             //$scope.selected.splice($scope.model.objectTypes[i].value);
            $scope.model.allItemsSelected = false;
            return; 
        } else {
            if ($scope.selected.indexOf($scope.model.objectTypes[i].value) == -1) {
                $scope.selected.push($scope.model.objectTypes[i].value);
            }
        }
    }
};

 // Fired when the checkbox "Show All" is checked
$scope.selectAll = function () {
    // Loop through all the object types and set their isChecked property
    for (var i = 0; i < $scope.model.objectTypes.length; i++) {
        $scope.model.objectTypes[i].isChecked = $scope.model.allItemsSelected;
    }
};

每当我点击该列表中的第一个“Show Activated”和“Show Inactivated”时,它就会添加到阵列中(选中)。   但如果我点击“Show InActivated”作为第一个。它没有添加到数组中。

删除相同的过程。

请任何人帮助实现此要求。

1 个答案:

答案 0 :(得分:0)

以下是您在工作版本中的代码+我改变了内容的评论。这是修改后的plunker

的链接
 $scope.selectObjectType = function () {
      $scope.selected = []; // clear previous state
      $scope.model.allItemsSelected = true; // all are selected unless...
     // If any object type is not checked, then uncheck the "allItemsSelected" checkbox
     for (var i = 0; i < $scope.model.objectTypes.length; i++) {
         if (!$scope.model.objectTypes[i].isChecked) { 
             //$scope.selected.splice($scope.model.objectTypes[i].value);
             $scope.model.allItemsSelected = false;
             // return; // if you return here all other select/unselect will be skipped
         } 
         else {
             if($scope.selected.indexOf($scope.model.objectTypes[i].value) == -1) {
                 $scope.selected.push($scope.model.objectTypes[i].value);
                }
         }

     }
 };

 // Fired when the checkbox "Show All" is checked
 $scope.selectAll = function () {
     // Loop through all the object types and set their isChecked property
     for (var i = 0; i < $scope.model.objectTypes.length; i++) {
         $scope.model.objectTypes[i].isChecked = $scope.model.allItemsSelected;
     }

     $scope.selectObjectType(); // add everything to array after select all - can be optimized
};