简体   繁体   English

使用多个选项以角度md-select设置所选项目

[英]Setting selected item in angular md-select with multiple option

Setting selected item in angular md-select with multiple option 使用多个选项以角度md-select设置所选项目

<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: data.roles包含值:

['account_admin', 'developer']

I need the item corresponding to role.value should be in selected state. 我需要与role.value相对应的项目处于选择状态。

Refer below image 参考下图 当前用户界面显示

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

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. 我不知道这是多么有效,或者这是否解决了相同的问题,但是您可以做的另一件事是在HTML中传递角色而不是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. 这使您可以在控制器中处理整个对象,并可以根据需要对其进行操作。

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

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