2014-10-11 61 views
0



我已經查看了'可能有您的答案的問題',但沒有任何運氣。沒有什麼工作對我來說:(

雖然看起來,我有一個非常簡單的例子,不順心的事...

我有以下HTML:使用ng選項時無法設置初始值

<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定義中似乎有些錯誤。
任何想法?


非常感謝!

+0

使用'ng-selected'初始化select的值。 https://docs.angularjs.org/api/ng/directive/ngSelected – 2014-10-11 07:43:55

回答

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 
+0

其實,ng-if屬性解決了我的情況(不含ng-select)。謝謝! – user1027133 2014-10-11 08:19:21

相關問題