javascript 如何在 AngularJS 中选择选项中的文本格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20967045/
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 19:43:40  来源:igfitidea点击:

How to format text in options for select in AngularJS?

javascriptjsonangularjs

提问by Melvin

I have the following json object:

我有以下 json 对象:

$scope.values = [
        {
            "id": 2,
            "code": "Code 1",
            "name": "Sample 1"
        },
        {
            "id": 4,
            "code": "Code 2",
            "name": "Sample 2"  
        },
        {
            "id": 7,
            "code": "Code 3",
            "name": "Sample 3"
        }
    ];

In select tag, I have this:

在选择标签中,我有这个:

<select name="c_id" ng-options="c.id as c.code for c in values"></select>

The generated select options is:

生成的选择选项是:

Code 1
Code 2
Code 3

Is there any way to format the text in the options like the following?

有什么方法可以在如下选项中格式化文本吗?

Code 1 -- Sample 1
Code 2 -- Sample 2
Code 3 -- Sample 3

Or I'll just have to prepare the values before attaching them to the model? Any help is appreciated. Thank you.

或者我只需要在将值附加到模型之前准备值?任何帮助表示赞赏。谢谢你。

回答by Cherniv

You can do it by using this syntax:

您可以使用以下语法来做到这一点:

ng-options="c.id as (c.code + ' -- '+ c.name) for c in values"

Example: http://jsfiddle.net/cherniv/6EkL7/1/

示例:http: //jsfiddle.net/cherniv/6EkL7/1/

Or someone may like next syntax:

或者有人可能喜欢下一个语法:

ng-options="c.id as [c.code,c.name].join(' -- ') for c in values"

Example: http://jsfiddle.net/cherniv/6EkL7/2/

示例:http: //jsfiddle.net/cherniv/6EkL7/2/

But in some cases there is rationality in using a Filter , like:

但在某些情况下,使用 Filter 是合理的,例如:

app.filter("formatter",function(){
    return function(item){
        return item.code+ " -- " + item.name;
    }
})

And: ng-options="c.id as c|formatter for c in values"

和: ng-options="c.id as c|formatter for c in values"

Example: http://jsfiddle.net/cherniv/K8572/

示例:http: //jsfiddle.net/cherniv/K8572/

回答by Maxim Shoustin

Sure, you can achieve that by invoke ng-repeatfor option,

当然,您可以通过调用ng-repeatfor来实现option

HTML

HTML

   <select> 
        <option ng-repeat="v in values" value="{{v.id}}">
          {{v.code}} -- {{v.name}}
        </option>
    </select>

JS

JS

the same

相同

Demo Fiddle

演示 Fiddle