2016-07-18 148 views
1

我有一個AngularJS項目列表與複選框,我有一個複選框,可以選擇所有項目。該功能僅用於選擇所有項目,我想要修改它以取消選擇所有項目。選擇/取消選擇所有複選框元素AngularJS

這是我的函數:

$scope.items.allItemsSelected = false; 
$scope.selectAll = function() { 
    for (var i = 0; i < $scope.itemsList.length; i++) { 
     $scope.temp.push($scope.itemsList[i].name); 
     console.log($scope.itemsList[i].name); 
     $scope.itemsList[i].isChecked = $scope.items.allItemsSelected; 
    } 
}; 

這是我的html:

<md-checkbox ng-model="items.allItemsSelected" 
      ng-change="selectAll()"> 
    Select all 
</md-checkbox> 

有誰知道如何修改這也取消元素的想法?

在此先感謝!

+0

你能提供陣列的一個例子'$ scope.itemsList'和在HTML中'ngRepeat'? –

回答

0

使用ng檢查的屬性。

<md-checkbox ng-model="items.allItemsSelected" ng-change="selectAll()"> 
    Select all 
</md-checkbox> 

checkbox1--

<md-checkbox ng-checked="isSelectAll" ng-model="items.allItemsSelected" ng-change="selectAll()"> 
    Select all 
</md-checkbox> 

checkbox2--

<md-checkbox ng-checked="isSelectAll" ng-model="items.allItemsSelected" ng-change="selectAll()"> 
    Select all 
</md-checkbox> 

JS:

$scope.isSelectAll = false; 
$scope.selectAll = function() { 
    if (!$scope.isSelectAll) { 
     $scope.isSelectAll = true; 
    } else { 
     $scope.isSelectAll = false; 
    } 
} 
+1

請注意'ngChecked'指令不應該和'ngModel'一起使用,因爲這可能會導致意外的行爲:https://docs.angularjs.org/api/ng/directive/ngChecked –

+0

當我取消選擇所有我想要的項目清空我的數組 – blaa

+0

當您取消選擇全部時,請將您的數組$ scope.itemsList = []置於其它selectAll函數的條件中。 –