Setting selected item in angular md-select with multiple option

佐手、 提交于 2019-12-06 15:33:36

问题


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


回答1:


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



回答2:


I dunno how valid this is or if this tackles the same problem but another thing that you could do is that in your HTML, pass in role instead of role.value. So it would look something like this:

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

This allows you to work with the entire object in your controller and you can manipulate it as you wish.



来源:https://stackoverflow.com/questions/42436358/setting-selected-item-in-angular-md-select-with-multiple-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!