使用ng-options时无法设置初始值

时间:2014-10-11 07:13:25

标签: javascript angularjs ng-options



我已经查看了可能有您答案的问题'没有运气。那里没什么用的:(

虽然看起来我有一个非常简单的案例,但出了点问题......

我有以下HTML:

<body>
  <div ng-controller="eventController as eventCtrl">
    <select ng-init="eventCtrl.userDetails.station = eventCtrl.eventDetails.stations[0]" ng-model="eventCtrl.userDetails.station" ng-options="o as o for o in eventCtrl.eventDetails.stations"></select>
  </div>
</body>

我的角度应用程序看起来像这样:

(function() {
var app = angular.module('eventRegistration', []);
var conn = new dataConn();

app.controller('eventController', ['dataService', function(dataService) {
    var eventCtrl = this;
    eventCtrl.eventDetails = {};
    eventCtrl.userDetails = {};


    dataService.getActiveEvents()
        .then(function (events) {
            eventCtrl.eventDetails = events[0];
        });        
}]);

app.service('dataService',['$q', function($q) {
    return {
        getActiveEvents: function() {
            var deferred = $q.defer();
            conn.getActiveEvents(function(events) {
                deferred.resolve(events)
            });
            return deferred.promise;
        }
    }
}]);
})();

我的eventCtrl.eventDetails对象最终会是这样的(我从服务器获取一组数组,现在只使用第一个):

    {
        "date":new Date(2014, 10, 2),
        "isActive": true,            
        "stations":['STATION_A', 'STATION_B'],                        
        "comments":""
    }

我尝试将用户所选电台的模型设置为eventCtrl.userDetails.station,并使用ng-init将其值发送到eventCtrl.eventDetails.stations的第一个电台。

值得一提的是,站点数据(实际上所有事件详细信息)都是异步获取的(使用延迟对象)。

我的代码的结果是一个带有&#39; STATION_1&#39;的选择框。和&#39; STATION_B&#39;值,但我有一个额外的第一个空值。我的ng-init定义似乎有些不对劲。
有任何想法吗?


非常感谢!

1 个答案:

答案 0 :(得分:0)

**ng-selected** will fit your need.
After making an async call to the server, assign the value which you want to initialize to a scope variable and use that variable in ng-selected.

`<select ng-if="selecteditem" ng-model="selecteditem" ng-options="item for item in items.name" ng-selected="selecteditem">
  </select>`

Here selecteditem is the variable which you want to initialize.

`myapp.controller('ItemCtrl',['$scope','$http', function($scope,$http)  //No I18N 
{  
  $scope.items = {"name":['first','second']}
  $scope.selecteditem = $scope.items.name[0]
}]);`


Since you mentioned an async call use **ng-if** such that select will be displayed only it has data.You can display some default values using **ng-if="!selecteditem"**

see the plnkr http://plnkr.co/edit/hv2OI1If1FMGhV0dgj9a?p=preview