简体   繁体   中英

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

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

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. Other 1,3 and 4 works as expected.

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

$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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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