How to format text in options for select in AngularJS?

All we need is an easy explanation of the problem, so here it is.

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>

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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/

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/

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

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

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

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

Method 2

Sure, you can achieve that by invoke ng-repeat for option,

HTML

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

JS

the same

Demo Fiddle

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply