AngularJS 选择多个选项 [英] AngularJS selecting multiple options

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

问题描述

所以,我尝试使用 vanilla JS 做的事情相当简单,但我使用的是 AngularJS,我想知道如何在框架内以最佳方式做到这一点.我想更新多选框中的选定选项.我不想添加或删除任何选项.这是我的 HTML 的样子:

So, What I'm trying to do is fairly simple with vanilla JS, but I'm using AngularJS and I would like to know how to do it the best way within the framework. I want to update the selected options in a multiple select box. I do not want to add or remove any of the options. Here is what my HTML looks like:

<select multiple>
    <option value="1">Blue</option>
    <option value="2">Green</option>
    <option value="3">Yellow</option>
    <option value="4">Red</option>
</select>

使用以下数组,我想以编程方式从此列表中选择/取消选择选项:

Using the following array, I'd like to programmatically select/deselect options from this list:

[{id:1, name:"Blue"},{id:4, name:"Red"}]

当我在示波器中设置这个数组时,我希望选择框取消选择任何不是蓝色或红色的东西,然后选择蓝色和红色.我在 Google Groups 上看到的标准响应是使用 ng-repeat.但是,我无法每次都重新创建列表,因为所选值的列表不完整.据我所知,AngularJS 没有这方面的机制,我不知道如何在不使用 jQuery 的情况下做到这一点.

When I set this array in the scope, I want the select box to deselect anything that is not Blue or Red and select Blue and Red. The standard response that I've seen on the Google Groups is to use ng-repeat. However, I can't recreate the list every time because the list of selected values is incomplete. As far as I can tell, AngularJS has no mechanism for this, and I'm at a loss as to how I would do this without resorting to using jQuery.

推荐答案

ngModel 非常棒!如果您将索引指定为模型 selectedValues

ngModel is pretty awesome! If you specify the indexes as a model selectedValues

<select multiple ng-model="selectedValues">

从您的列表(selected)构建在 $watch

built from your list (selected) in a $watch

$scope.$watch('selected', function(nowSelected){
    // reset to nothing, could use `splice` to preserve non-angular references
    $scope.selectedValues = [];

    if( ! nowSelected ){
        // sometimes selected is null or undefined
        return;
    }

    // here's the magic
    angular.forEach(nowSelected, function(val){
        $scope.selectedValues.push( val.id.toString() );
    });
});

ngModel 会自动为你选择它们.

ngModel will automatically select them for you.

请注意,此数据绑定是单向的(selected 到 UI).如果您想使用

发送“验证码”获取 | 15天全站免登陆