0

At the moment I have a select, but i need to have custom styling for my options, that requires me to change my setup a bit.

At the moment I have

 <select ng-model="vm.selectedStation"
         ng-options="s.stationName for s in  vm.nearbyStations" .....>
 </select>

Now I am changing it to

<select ng-model="vm.selectedStation">
    <option ng-repeat="s in vm.nearbyStations" value="{{s}}">            
        {{s.stationName}}
    </option>
</select>

It visibly shows the same, but the value is different. I require ng-model to be s. to be the object, but instead it shows as the s.stationName May I ask how do I set the value properly

2 Answers 2

1

Use the ng-value directive:

<select ng-model="vm.selectedStation">
    ̶<̶o̶p̶t̶i̶o̶n̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶s̶ ̶i̶n̶ ̶v̶m̶.̶n̶e̶a̶r̶b̶y̶S̶t̶a̶t̶i̶o̶n̶s̶"̶ ̶v̶a̶l̶u̶e̶=̶"̶{̶{̶s̶}̶}̶"̶>̶
    <option ng-repeat="s in vm.nearbyStations" ng-value="s">            
        {{s.stationName}}
    </option>
</select>

Interpolation with curly brackets {{ }} converts the expression to a string. The ng-value directive evaluates the expression and retains its type.

For more information, see

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

Comments

0

Simply use ng-value on each <option> to assign directly to each constituent of vm.nearbyStations.

See an example usage below.

(As an aside, your HTML appears to have an unpaired </option>.)

angular
  .module('app', [])
  .controller('ctrl', function () {
    this.nearbyStations = [
      { stationName: 'a' },
      { stationName: 'b' },
      { stationName: 'c' },
    ];
  });
<script src="https://unpkg.com/[email protected]/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as vm">
  <select ng-model="vm.selectedStation">
    <option ng-repeat="s in vm.nearbyStations" ng-value="s">{{ s.stationName }}</option>
  </select>
  <pre>selectedStation = {{ vm.selectedStation }}</pre>
</div>

Comments

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.