Tyler Durden
Tyler Durden

Reputation: 2171

<select> doesn't have a selected value

I try to set the value of my select dynamically in the controller the following way:

angular.module('vocabApp.controllers', []).
controller('indexController', function ($scope, dictionaryHandler) {
$scope.expressions = [
  { expression: "", meanings: ["first", "second"], selected: "" }];

$scope.counter = 0;



$scope.add = function (expressionString, expressionObject) {

    if (expressionString.length == 1) {
        $scope.expressions.push({ expression: "", meanings: [""] });
    }

    dictionaryHandler.sendJsonpRequestToGetMeanings(expressionString, function (meaningsWeAcquired) {
        alert("callback called!");
        expressionObject.meanings = meaningsWeAcquired;
        expressionObject.selected = expressionObject.meanings[0];

    });


};

});

The odd thing is that the content of "meaningsWeAcquired" shows up in the select list, but there is no default selected value. Here's the html:

<select ng-init="option.selected = item.meanings[0]" ng-model="option.selected" ng-options="option as option for option in item.meanings"></select>

On page load the default value is "first", so I don't get why the same thing doesn't work when I set the object's "selected" field from the callback method.

Upvotes: 0

Views: 135

Answers (1)

JMansar
JMansar

Reputation: 208

I can see that you are setting expressionObject.selected in the sendJsonpRequestToGetMeanings callback, but in the HTML the select ng-model attribute is set to "option.selected", which does not point to the value you set before. I guess that the select element is wrapped by the ng-repeat directive and "item" references current expresssionObject.

So you should try changing:

ng-model="option.selected"

to

ng-model="item.selected"

Upvotes: 1

Related Questions