[英]How to pass <option> in a <select> list into function whilst keeping track of selected options?
I have a data structure that looks like this: 我有一个看起来像这样的数据结构:
var items = [{
name: 'someName',
description: 'someDescription'
},
{
name: 'someOtherName',
description: 'someOtherDescription'
}];
And I want to present them in a select box , track which objects are selected as well as allow the user to double click on an item and pass the item to a function - so I can try do this: 我想在选择框中显示它们 , 跟踪 选择了 哪些对象 ,以及允许用户双击某个项目并将该项目传递给函数 -因此我可以尝试执行以下操作:
<select multiple="true"
ng-model="myModel"
ng-options="item.name + ' ' + item.description for item in items"
ng-dblclick="testFunction(item)">
</select>
My testFunction
looks like this (in reality it's doing a little bit more than just dumping the item, but we can ignore that for the purpose of the question): 我的
testFunction
看起来像这样(实际上,它所做的不只是转储项目,但出于问题的目的,我们可以忽略它):
function testFunction(item) {
console.log(item);
};
The list displays fine, however when the logging line in my testFunction()
is executed, it is just printing undefined. 该列表显示正常,但是当执行我的
testFunction()
的日志记录行时,它只是打印未定义。 myModel
does keep track of which objects are selected. myModel
确实跟踪选择了哪些对象。
I then tried a slightly different approach. 然后,我尝试了一种稍微不同的方法。 I tried to populate the
<option>
list using ng-repeat: 我试图使用ng-repeat填充
<option>
列表:
<select multiple="true" ng-model="myModel">
<option ng-repeat item in items" ng-dblclick="testFunction(item)">
{{item.name}} - {{item.description}}
</option>
</select>
Now this almost gets me over the line. 现在,这几乎使我无法接受。 My
testFunction()
now receives the object fine. 我的
testFunction()
现在可以很好地接收对象了。 However, now my myModel
is only populating with strings of whatever is in the text part of the <option>
tag. 但是,现在
myModel
仅使用<option>
标记的文本部分中的字符串填充。
It seems like I am unable to get both of these things happening at once. 看来我无法同时实现这两种情况。
Is anyone able to help? 有人能帮忙吗? Let me know if you need any more information.
让我知道您是否需要更多信息。
<select multiple="true" ng-model="myModel">
<option ng-repeat="item in items" ng-dblclick="testFunction(item)"value="{{item}}">
{{item.name}} - {{item.description}}
</option>
</select>
You need to be setting the value attribute on the options element to the item object. 您需要将options元素上的value属性设置为item对象。 otherwise it will default to whatever is being displayed.
否则,它将默认为正在显示的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.