[英]How can I auto select the existing data in a Angular Material Checkbox?
I want to auto select the Checkbox if it already exists in the model 如果模型中已经存在该复选框,我想自动选择该复选框
I tried with the following code 我尝试了以下代码
Controller 控制者
$scope.model = {
items: [{"key":1, "value": "One"},{"key":2, "value": "Two"},{"key":3,
"value": "Three"},{"key":4, "value": "Four"},{"key":5, "value": "Five"}]
};
$scope.selected = [{"key":2, "value": "Two"},{"key":5, "value": "Five"}];
$scope.toggle = function(item, list) {
var idx = list.indexOf(item);
if (idx > -1) {
list.splice(idx, 1);
} else {
list.push(item);
}
};
$scope.exists = function(item, list) {
return list.indexOf(item) > -1;
};
HTML 的HTML
<div flex="25" ng-repeat="item model.items">
<md-checkbox ng-checked="exists(item, selected)"
ng-click="toggle(item, selected)">
{{ item.value }}
</md-checkbox>
</div>
But the checkbox for Key '2' and '5' not selected by default. 但是默认情况下未选中键“ 2”和“ 5”的复选框。
If I replace the following code, 如果我替换以下代码,
$scope.exists = function (item, list) {
for (var i = 0; i < list.length; i++) {
if (list[i].key === item.key) {
return true;
}
}
return false;
};
It selects 2 and 5 while page loading but not able un check both. 它在页面加载时选择2和5,但无法同时取消选中两者。 Other 1,3 and 4 works as expected.
其他1,3和4正常工作。
A solution off the top of my head 一种解决方案
<div flex="25" ng-repeat="item model.items">
<md-checkbox ng-model="item.selected"
ng-click="toggle(item, selected)">
{{ item.value }}
</md-checkbox>
</div>
so use ng-model and to set default 所以使用ng-model并设置默认值
$scope.model = {
items: [{"key":1, "value": "One"},{"key":2, "value": "Two", selected: true},{"key":3,
"value": "Three"},{"key":4, "value": "Four"},{"key":5, "value": "Five", selected: true}]
};
later to get a selected items you just need to use 以后要获得选定的物品,您只需要使用
$scope.model.items.filter(function(item){return item.selected});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.