将两个额外的选项添加到带有 ngOptions 的选择列表中 [英] Add two extra options to a select list with ngOptions on it
问题描述
我有一堆选择列表,我正在尝试为它们添加一个无"和一个标题选项.代码如下:
I have a bunch of select lists and I'm trying to add a "none" and a title option to them. The code looks like so:
<select ng-options="value.name for value in values" ng-model="selection">
<option value="" disabled>{{title}}</option>
<option value="">None</option>
</select>
目前,我无法将它们添加到数据中,因此我正在尝试找到一种方法来使其正常工作.当我第一次加载它们时,无"选项不存在.标题在那里并且按预期工作,但似乎我无法在此选择列表中添加两个空白条目.
For right now, I cannot add them to the data so I am trying to find a way to get this working. When I load them for the first time, the "none" option is not there. The title is there and works as intended, but it seems I cannot add two blank entries to this select list.
最简单的方法是将无"选项添加到数据中,但这对我来说是不可能的.有没有合适的方法来实现我想要的?
The easiest way would be to have the "none" option added to the data but it's not a possibility for me. Is there a proper way to achieve what I want?
推荐答案
没错,你只能有一个硬编码元素.<option ng-repeat>
从技术上讲是可以完成的,但是该方法仅完全支持绑定到字符串,因此绑定到对象会变得非常麻烦,就像您正在做的那样.
That's correct, you can only have one hard-coded element. <option ng-repeat>
can technically be done, but that method only cleanly supports binding to strings, so it would get very kludgey to bind to objects, as you're doing.
你说你不能在数据中添加None",但你可以做下一件最好的事情:将它添加到数组 ng-options 使用过滤器进行迭代:
You say you can't add "None" to the data, but you can do the next best thing: prepend it to the array ng-options is iterating across, using a filter:
app.filter('addNone', function () {
return function(input) {
var newArray = input.slice(0); //clone the array, or you'll end up with a new "None" option added to your "values" array on every digest cycle.
newArray.unshift({ name: "None" });
return newArray;
};
})
然后像这样使用过滤器:
Then use the filter like this:
<select class="form-control" ng-options="value.name as value.name for value in filter.values | addNone" ng-model="filter.selected" ng-change="goSearch()">
<option value="" disabled>{{filter.name}}</option>
</select>
这篇关于将两个额外的选项添加到带有 ngOptions 的选择列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!