Reputation: 467
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
Upvotes: 0
Views: 37
Reputation: 48968
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
ng-value
Directive API Reference<select>
- Using ngValue
to bind the model to an array of objectsUpvotes: 1
Reputation: 3664
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>
Upvotes: 0