javascript ngOptions 可以调用函数来获取显示文本吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21785021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:41:18  来源:igfitidea点击:

can ngOptions call a function to get display text?

javascriptangularjs

提问by Brian Oliver

I have a selecttag that I'm binding to an array of radio station objects using AngularJS. My object has the following properties:

我有一个select标签,我使用 AngularJS 将它绑定到一组广播电台对象。我的对象具有以下属性:

{
    id: 'WXYZ',
    name: 'Radio Station Name (optional)',
    frequency: '89.7 FM'
}

I'd like each element in the dropdown to show "{id} - {name} - {frequency}" as the display text, but since the name property is optional, I'd like to avoid double dashes in the event that an object has no value for its name.

我希望下拉列表中的每个元素都显示“{id} - {name} - {frequency}”作为显示文本,但由于 name 属性是可选的,我想避免出现双破折号对象的名称没有值。

I was able to get this working:

我能够得到这个工作:

<select ng-model="StationPreference" ng-options="s.id+ ' - ' + s.name + ' - ' + s.frequency for s in stations">
    <option value="">-- select --</option>
</select>

What are the rules/guidelines/best practices for calling a function inside ng-options? I'd like to do something like getDisplayText(s)-- what makes the expression "valid for angular"? does the function have to be defined inside the scope? Can it be any externally defined function? Is this the best approach for the desired functionality?

在 ng-options 中调用函数的规则/指南/最佳实践是什么?我想做一些类似的事情getDisplayText(s)- 是什么让表达“对角度有效”?函数是否必须在作用域内定义?它可以是任何外部定义的函数吗?这是实现所需功能的最佳方法吗?

采纳答案by squid314

Is it possible to call a function inside ng-options?

是否可以在 ng-options 中调用函数?

Short answer: yes. (A quick test would have also answered this for you.)

简短的回答:是的。(快速测试也可以为您回答这个问题。)

Longer answer: ng-optionsallows you to specify any arbitrary expression (as long as it is valid for Angular) in both the labeland valueslots of the options comprehension (see the docs). This means you can specify a function available on the scope to produce your labelstring.

更长的答案:ng-options允许您在选项理解的thelabelvalueslot 中指定任何任意表达式(只要它对 Angular 有效)(请参阅文档)。这意味着您可以指定作用域上可用的函数来生成label字符串。

Update:

更新:

The value used by ng-optionsas the label is generated by consuming the string you provided and passing it to $parseto generate an evaluable expression which will be called later. This expression is then run against the scopewith the additional local values from the looping to actually generate the string which is displayed. The expression can do basically anything that you might put in an {{ interpolation }}(interpolations are done with $parsetoo, unless I'm mistaken), which can include concatenating strings, calling functions visible on the scope (which could actually exist on a parent scope and be inherited), running Angular filters (e.g. lowercaseor json), etc.

用作ng-options标签的值是通过使用您提供的字符串并将其传递$parse给以生成稍后将调用的可评估表达式来生成的。然后将此表达式scope与循环中的附加本地值一起运行,以实际生成显示的字符串。该表达式基本上可以执行您可能放入的任何操作{{ interpolation }}(也可以使用插值$parse,除非我弄错了),其中可以包括连接字符串、调用作用域上可见的函数(实际上可以存在于父作用域中并被继承) )、运行 Angular 过滤器(例如lowercasejson)等。

In terms of best practices, I would say that your initial display of s.id+ ' - ' + s.name + ' - ' + s.frequencyis probably fine as an expression rather than extracting it to a function on the scope. However, it is mildly complex and adding the condition you desire would definitely push it over the edge to a function (even though it's possible as an expression using a ternary). In general if the display logic is complex or if the same logic is used in multiple places, it should be extracted to a function, or even a filter depending on how generic it is.

就最佳实践而言,我会说您的初始显示s.id+ ' - ' + s.name + ' - ' + s.frequency可能作为表达式很好,而不是将其提取到作用域上的函数中。然而,它有点复杂,添加你想要的条件肯定会将它推到一个函数的边缘(即使它可以作为使用三元的表达式)。一般来说,如果显示逻辑很复杂,或者如果在多个地方使用相同的逻辑,则应该根据它的通用程度将其提取为一个函数,甚至一个过滤器。

回答by koolunix

this worked for me:

这对我有用:

<select ng-model="myForm.car"
        ng-options="obj.id as genName(obj.id,obj.name) for obj in myForm.options">
    <option value="">Select...</option>
</select>


$scope.myForm.options = [
    { id : "nissan", name: "Nissan" },
    { id : "toyota", name: "Toyota" },
    { id : "fiat"  , name: "Fiat" }
];

$scope.genName = function(id,name) {
    return id + ' ' + name;
}

回答by NicolasP

It is a bit hidden in the documentation but it can be achieved easily.

它在文档中有点隐藏,但可以轻松实现。

In your case, it is the syntax documented as :

在您的情况下,它的语法记录为:

select as label for value in array

And so for you need:

所以你需要:

<select ng-model="StationPreference" ng-options="s as getDisplayText(s) for s in stations">
    <option value="">-- select --</option>
</select>