How to format text in options for select in AngularJS?

angularjs, javascript, json

Solution

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/

Problem

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.

Original source