Search code examples
javascriptangularjsng-optionsangularjs-select

ng-selected not working with ng-options or ng-repeat


I have a form which the user can fill out to get directions to a destination using google maps. There are 350 possible set destinations that the user can chose from. They can chose this destination by clicking on a pin on the google map or else from a select menu in the form.

When they click on the pin on the google map I would like the select menu to change to the destination.

I am trying to use ng-selected for this however it isn't working.

Any help would be grately appreciated. Thank you.

View

   <div id="select_destination">
        <select data-ng-model="selectedDestination" 
                ng-options="station.stationID as station.stationShortAddress for station in allStationsMapData track by station.stationID" 
                data-ng-change="selectDestination(selectedDestination)"
                ng-selected="station.stationID == selectedDestination">
        </select>
    </div>

Controller

A function called getDirections is called when a user clicks on a station on the map (not selecting from the select menu). This should change the currently selected item of the select menu but doesn't. (Note: the function is executing correctly passing in the right stationID.)

$scope.getDirections = function(stationLat, stationLng, stationID){ 
    //update the select menu model to the chosen stationID.
    $scope.selectedDestination = stationID;     
};

Extra info:

I also tried using ng-selected with ng-repeat however it didn't work either.

<select data-ng-model="selectedDestination" data-ng-change="selectDestination(selectedDestination)">
    <option ng-repeat="stationMapData in allStationsMapData" 
        value="{{stationMapData.stationID}}" 
        ng-selected="{{stationMapData.stationID == selectedDestination}}">
        {{stationMapData.stationShortAddress}}
    </option>
</select>

Solution

  • change ng-selected="station.stationID == selectedDestination" to ng-selected="selectedDestination".

    Or use ng-init instead of ng-selected.(It's more clear way.)

    ng-init="selectedDestination = 'key of what you want'"
    

    Reference Fiddle.

    FIDDLE(First case)
    FIDDLE(Second case)