Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : get select label without modifying ng-model

I'm currently stuck with a problem which seems simple :

Controller :

$scope.fruits = [{
    name: 'AP',
    label: 'Apple'
  }, {
    name: 'BA',
    label: 'Bananas'
  }];   

HTML code :

<select
    ng-model="meal.fruit"
    ng-options="fruit.name as fruit.label for fruit in fruits">
</select>

<p>Fruit : {{meal.fruit}}</p>

Problem is, this displays

Fruit : BA

Instead of

Fruit : Bananas

I can't modify ng-option to "fruit as fruit.label" because I need my model "meal.fruit" to be "AP" or "BA" (because it is a java enum deserialize by Jackson, and it requires the Enum value).

JSFiddle

In summary, I need meal.fruit to be "BA" and I also want to be able to display the selected value "Bananas" somewhere else.

What can I do ?

EDIT :

The solution that worked for me was found by Maxim Shoustin, (many thanks !) :

I modified my code to have the following :

http://jsfiddle.net/2qfSB/77/

And then I modified my submit method to add the following :

$scope.meal.fruit = $scope.meal.fruit.name;
like image 835
Baptiste Avatar asked Oct 21 '22 21:10

Baptiste


1 Answers

Just change ng-options:

ng-options="fruit.label as fruit.label for fruit in fruits">

Fixed Demo: Fiddle

as a side note

You can set by default 1st element to avoid empty combo by using ng-init:

<select
        ng-model="meal.fruit"
        ng-options="fruit.label as fruit.label for fruit in fruits"
        ng-init="meal.fruit = fruits[0].label"
    >

Demo: Fiddle

like image 149
Maxim Shoustin Avatar answered Oct 23 '22 14:10

Maxim Shoustin