0

I would like to set different text / value for a dropdown I have with AngularJS. Currently both the text and the value are same by using this syntax:

<select name="flightNum" class="form-control" ng-model="model.flight"
       ng-options="v.Value as v.Text for v in flights" required></select>

I tried this approach:

<select name="flightNum" class="form-control" ng-model="model.flight" 
          ng-options="v.Value as v.Text for v in flights" required>
    <option ng-repeat="v in flights" value="{{v.Value}}"> {{v.Text}}</option>
</select>

But I've got the same text/value combination. What do I need to change to make this work with AngularJS?

3
  • please see here jsbin.com/coculu/1/edit seems to be fine your fist option Commented Oct 29, 2014 at 22:19
  • @sylwester in the example you have, if you inspect the element you'll see that the value is 0 and 1 for the dropdown items gyazo.com/06a5627b8b1ce76f95b1ad918cecb0de Commented Oct 29, 2014 at 22:25
  • 1
    you don't have to worry about that please see jsbin.com/coculu/2/edit model.flight is binding to proper value Commented Oct 29, 2014 at 22:27

2 Answers 2

1

As long as your $scope.flights is setup properly, the first syntax you showed should work. I've setup a plunker to show this in action at http://plnkr.co/edit/PIXZZO81aQKj4kmngoXy?p=preview

It has the following data structure for $scope.flights:

  $scope.flights = [{
    value: 'val1',
    text: 'text1'
  }, {
    value: 'val2',
    text: 'text2'
  }, {
    value: 'val3',
    text: 'text3 '
  }]

Then, the select can be written essentially as you have it (i used lowercase value and text on accident, but just make sure it matches between the controller and the html):

<select name="flightNum" class="form-control" ng-model="model.flight" ng-options="v.value as v.text for v in flights" required></select>

With this setup, the dropdown is populated with the values contained in the "text" fields, but selecting something sets the "value" into the model.flight variable. You can see this in the Plunker mentioned above.

Is this the behavior you're wanting? If not, what is happening that is different/unexpected?

Sign up to request clarification or add additional context in comments.

Comments

1

you need to add track by in the ng-options

<select name="flightNum" class="form-control" ng-model="model.flight"
       ng-options="v.Value as v.Text for v in flights track by v.Value" required>
</select>

and that's it.

2 Comments

Thanks! I had spent too much time trying to figure this out. Appreciate the answer.
glad that this helped you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.