<select>没有选定的值</select>

时间:2014-07-12 20:39:14

标签: angularjs angularjs-ng-options

我尝试以下列方式在控制器中动态设置我的选择值:

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];

    });


};

});

奇怪的是,&#34;意义的内容我们获得了&#34;显示在选择列表中,但没有默认选定值。这是html:

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

在页面加载时,默认值是&#34;首先&#34;,所以我不明白为什么当我设置对象时,同样的事情是行不通的?&#34;选择&#34;回调方法中的字段。

1 个答案:

答案 0 :(得分:1)

我可以看到你在sendJsonpRequestToGetMeanings回调中设置了expressionObject.selected,但是在HTML中,select ng-model属性设置为&#34; option.selected&#34;,它没有指向你的值之前设定。我猜选择元素是由ng-repeat指令和&#34; item&#34;包裹的。引用当前的expresssionObject。

所以你应该尝试改变:

ng-model="option.selected"

ng-model="item.selected"