Angularjs选择对象多个选项 [英] Angularjs select multiple options from object

查看:129
本文介绍了Angularjs选择对象多个选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图选择多个选项中angularjs有关对象的值

Trying to select multiple options in angularjs regarding to object values

下面是一个code:

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工作样本

(Non)working sample on jsfiddle​

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

推荐答案

您正在尝试使用一个选择多像一个复选框列表,这是一个有些奇怪。多选择输出数组。你不能把NG-模型上像一个选项标签,这是不言而喻的选择本身。如此以来,选择将输出值的数组,你需要通过值循环,在你的范围内更新的节点。

You're trying to use a select multiple like a checkbox list, which is a little strange. Multi-selects output an array. You can't put ng-model on an option tag like that, it goes on the select itself. So since the select will output an array of values, you'll need to loop through the values and update the nodes in your scope.

这里有一个普拉克证明了code

和这里的code:

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

我希望帮助。

这篇关于Angularjs选择对象多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆