繁体   English   中英

如何在“角度材质”复选框中自动选择现有数据?

[英]How can I auto select the existing data in a Angular Material Checkbox?

如果模型中已经存在该复选框,我想自动选择该复选框

我尝试了以下代码

控制者

$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

<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>

但是默认情况下未选中键“ 2”和“ 5”的复选框。

如果我替换以下代码,

$scope.exists = function (item, list) {
 for (var i = 0; i < list.length; i++) {
        if (list[i].key === item.key) {
            return true;
        }
    }
    return false;
};

它在页面加载时选择2和5,但无法同时取消选中两者。 其他1,3和4正常工作。

一种解决方案

<div flex="25" ng-repeat="item model.items">
    <md-checkbox  ng-model="item.selected" 
        ng-click="toggle(item, selected)">
    {{ item.value }} 
    </md-checkbox>
</div>

所以使用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}]
};

以后要获得选定的物品,您只需要使用

$scope.model.items.filter(function(item){return item.selected});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM