mardi 30 août 2016

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)">
     
    </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.




Aucun commentaire:

Enregistrer un commentaire