一尘不染

AngularJS从对象中选择多个选项

angularjs

尝试在angularjs中选择关于对象值的多个选项

这是一个代码:

myapp.controller('myctrl', [
        '$scope',
        function ($scope) {
            $scope.query = {
                Statuses: {
                    Draft: true,
                    Live: true,
                    Pending: true,
                    Archived: false,
                    Deleted: false
                }
            };


        }
    ]);​

和html

<div ng-controller="myctrl">
<select multiple>
    <option value="Draft" ng:model="query.Statuses['Draft']">Draft</option>
    <option value="Pending" ng:model="query.Statuses.Pending">Pending</option>
    <option value="Live" ng:model="query.Statuses.Live">Live</option>
    <option value="Archived" ng:model="query.Statuses.Archived">Archived</option>
    <option value="Deleted" ng:model="query.Statuses.Deleted">Deleted</option>
</select>

    {{query | json}}
</div>

jsfiddle上的(非)工作示例

http://jsfiddle.net/andrejkaurin/h9fgK/


阅读 187

收藏
2020-07-04

共1个答案

一尘不染

您尝试使用选择倍数(如复选框列表),这有点奇怪。多选输出一个数组。您不能将ng-
model放在这样的选项标签上,而是放在选择本身上。因此,由于select将输出值数组,因此您需要遍历这些值并更新作用域中的节点。

这是一个演示代码的代码

这是代码:

JS

function inArray(x, arr) {
  for(var i = 0; i < arr.length; i++) {
    if(x === arr[i]) return true;
  }
  return false;
}

app.controller('MainCtrl', function($scope) {
   $scope.query = {
                Statuses: {
                    Draft: true,
                    Live: true,
                    Pending: true,
                    Archived: false,
                    Deleted: false
                }
            };
  $scope.selectionsChanged = function(){
    for(var key in $scope.query.Statuses) {
      $scope.query.Statuses[key] = inArray(key, $scope.selectedValues);
    }
  };
});

的HTML

<select multiple ng-model="selectedValues" ng-change="selectionsChanged()">
    <option value="Draft" ng-selected="query.Statuses.Draft">Draft</option>
    <option value="Pending" ng-selected="query.Statuses.Pending">Pending</option>
    <option value="Live" ng-selected="query.Statuses.Live">Live</option>
    <option value="Archived" ng-selected="query.Statuses.Archived">Archived</option>
    <option value="Deleted" ng-selected="query.Statuses.Deleted">Deleted</option>
</select>
<br/>
    {{query | json}}

希望对您有所帮助。

2020-07-04