Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/14552976/how-to-get-option-text-value-using-angularjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...