AngularJS 选择多个选项 [英] AngularJS selecting multiple options
问题描述
所以,我尝试使用 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).如果您想使用 UI 来构建您的列表,我建议重构数据(或使用另一个
$watch
但这些可能很昂贵).
Note that this data binding is one-way (selected
to UI). If you're wanting to use the <select>
UI to build your list, I'd suggest refactoring the data (or using another $watch
but those can be expensive).
是的,selectedValues
需要包含字符串,而不是数字.(至少它对我有用:)
Yes, selectedValues
needs to contain strings, not numbers. (At least it did for me :)
完整示例位于 http://jsfiddle.net/JB3Un/
这篇关于AngularJS 选择多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!