我在 ng-repeat 中有一个复选框列表:
<div ng-repeat="item in results">
<label class="inlinelabel checkbox">
<input type="checkbox" ng-model="selected[item.id]"><i></i>
</label>
</div>
我想通过单击 ng-repeat 之外的单个复选框来选中所有复选框。
<label> Select All </label>
<input type="checkbox" data-ng-model="selectedAll" ng-click="checkAll()">
我尝试了 Controller 中的代码,但它不起作用。
$scope.checkAll=()=>{
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.employees,function (selected) {
selected[selected.id] = $scope.selectedAll;
});
}
最佳答案
这里的其他答案确实使所有复选框都“选中”,但我认为这个想法是让底层模型也发生变化,而这些答案却没有做到这一点。
这是因为 Angular 不会在 ng-checked
更改时更改模型。相反,“全选”的正确方法是更改模型 - View 紧随其后。
<button ng-click="selectAll()">select all</button>
<div ng-repeat="item in items">
<label>
{{item.n}}:
<input type="checkbox" ng-model="selected[item.id]">
</label>
</div>
并且在 Controller 中,只需将selected
中的所有项目设置为true
:
$scope.selected = {};
$scope.selectAll = function(){
for (var i = 0; i < $scope.items.length; i++) {
var item = $scope.items[i];
$scope.selected[item.id] = true;
}
};
ViewModel“驱动”View(双向指令除外,例如 ng-model
,它允许 View 更改 ViewModel,通常基于用户交互),因此每当您想更改某些内容时,首先问自己“我希望 ViewModel 看起来像什么”,而不是 View 应该是什么样子。 View 将遵循 ViewModel。
关于javascript - 选择 ng-repeat 中的所有复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29002278/