Search code examples
angularjssails.jsangular-materialmd-select

Setting selected item in angular md-select with multiple option


Setting selected item in angular md-select with multiple option

<md-select multiple ng-model="Reg.roles" placeholder="Please select roles" required>
    <md-option ng-repeat="role in roles" value="{{role.value}}" ng-selected="{{ role.value === '<%= data.roles %>' ? 'true' : 'false' }}">{{ role.name }}</md-option>
</md-select>

in my controller

 $scope.roles = [{
        "name": "Account Admin",
        "value": "account_admin"
    }, {
        "name": "Developer",
        "value": "developer"
    },


    {
        "name": "Analyst",
        "value": "analyst"
    }
];

in view

data.roles contains value:

['account_admin', 'developer']

I need the item corresponding to role.value should be in selected state.

Refer below image current ui showing


Solution

  • Finally i found the solution, in my controller i wrote this:

    var current_roles       = '<%=data.roles%>'; // current value from db as array
    
    $scope.Reg.roles = []; //initialize array
    
    angular.forEach($scope.roles, function(val1, key1) {
        if(current_roles.indexOf(val1['value']) !== -1) // check if item in current array
        {
            $scope.Reg.roles.push(val1['value']); //setting to select items
        }
    });