【问题标题】:Setting selected item in angular md-select with multiple option使用多个选项在角度 md-select 中设置所选项目
【发布时间】:2017-02-24 10:31:29
【问题描述】:

使用多个选项在角度 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>

在我的控制器中

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


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

在视图中

data.roles 包含值:

['account_admin', 'developer']

我需要 role.value 对应的项目应该处于选中状态。

参考下图

【问题讨论】:

  • 使用 ng 选项有时选项不起作用

标签: angularjs sails.js angular-material md-select


【解决方案1】:

最后我找到了解决方案,在我的控制器中我写了这个:

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】:

    我不知道这有多有效,或者这是否解决了同样的问题,但您可以做的另一件事是在您的 HTML 中,传递角色而不是角色值。所以它看起来像这样:

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

    这使您可以在控制器中使用整个对象,并且可以随意操作它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 2020-06-17
      • 2018-07-31
      • 2017-07-02
      • 1970-01-01
      • 2017-11-11
      • 2020-08-14
      相关资源
      最近更新 更多