如何在AngularJS中选择的选项中格式化文本? [英] How to format text in options for select in AngularJS?

查看:107
本文介绍了如何在AngularJS中选择的选项中格式化文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json对象:

I have the following json object:

$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>

生成的选择选项为:

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.

推荐答案

您可以使用以下语法进行操作:

You can do it by using this syntax:

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

示例: 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"

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

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

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

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

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

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

这篇关于如何在AngularJS中选择的选项中格式化文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆