繁体   English   中英

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

[英]Unable to set initial value when using 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的第一个站点。

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

我的代码的结果是一个带有'STATION_1'和'STATION_B'值的选择框,但我还有一个第一个空值。 在ng-init定义中似乎出了点问题。
有任何想法吗?


非常感谢!

**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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM