Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get option text value using AngularJS?

Tags:

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?

like image 348
Adrian Gunawan Avatar asked Jan 27 '13 22:01

Adrian Gunawan


2 Answers

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

Controller

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

HTML

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

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

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

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

like image 200
bmleite Avatar answered Oct 19 '22 07:10

bmleite


Instead of ng-options="product as product.label for product in products"> in the select element, you can even use this:

<option ng-repeat="product in products" value="{{product.label}}">{{product.label}} 

which works just fine as well.

like image 35
webacs.com.au Avatar answered Oct 19 '22 08:10

webacs.com.au