How to format text in options for select in AngularJS?

后端 未结 2 1976
眼角桃花
眼角桃花 2021-02-12 11:44

I have the following json object:

$scope.values = [
        {
            \"id\": 2,
            \"code\": \"Code 1\",
            \"name\": \"Sample 1\"
                


        
相关标签:
2条回答
  • 2021-02-12 12:27

    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/

    0 讨论(0)
  • 2021-02-12 12:41

    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

    0 讨论(0)
提交回复
热议问题