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?
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With