Adrian Gunawan Adrian Gunawan - 5 months ago 16
AngularJS Question

How to get option text value using AngularJS?

I'm trying to get a text value of an option list using AngularJS

Here is my code snippet

<div class="container-fluid">
Sort by:
<select ng-model="productList">
<option value="prod_1">Product 1</option>
<option value="prod_2">Product 2</option>
</select>
</div>

<p>Ordered by: {{productList}}</p>


{{productList}}
returns the value of the option, eg: prod_1. I'm trying to get the text value 'Product 1'. Is there a way to do this?

Answer

The best way is to use the ng-options directive on the select element.

On your Controller:

function Ctrl($scope) {
  // sort options
  $scope.products = [{
    value: 'prod_1',
    label: 'Product 1'
  }, {
    value: 'prod_2',
    label: 'Product 2'
  }];   
}

On your HTML:

<select ng-model="productList" 
        ng-options="product as product.label for product in products">           
</select>

This will bind the selected product object to the ng-model property - productList. After that you can use this:

<p>Ordered by: {{productList.label}}</p>

jsFiddle: http://jsfiddle.net/bmleite/2qfSB/