我有一個「狀態選擇」指令,用一個基於countryCode的狀態列表填充select元素。該指令監視countryCode上的更改以更新提供給ng選項的屬性。加載ng-options前更新模型時的選擇選項
我現在想從我的控制器設置model.countryCode和model.sateCode,但是當countryCode更改時填充狀態選擇時,在選項獲得加載的機會之前更新模型值。
我怎樣才能確保select加載選項後,選擇在其ng模型中引用的選項?
這裏是我的指令:
.directive('stateSelect', [ 'CDN_VIEW', 'locationService', function(CDN_VIEW, locationService) {
return {
restrict: 'E',
scope: {
'ngModel': '=',
'country': '=',
},
link: function stateSelect($scope, elements, attrs) {
$scope.states = null;
function loadCountryStates(countryCode) {
if (!countryCode) {
return false;
}
$scope.ngModel = undefined;
locationService.getCountryStates(countryCode).then (function getStates(states) {
$scope.states = states;
});
}
$scope.$watch('country', loadCountryStates);
},
templateUrl: 'states.html'
};
} ])
模板:
<select ng-model="ngModel" ng-options="s.code as s.name for s in states">
<option value="" disabled>select state</option>
</select>
這裏的使用指令:
<state-select ng-model="info.stateCode" country="info.countryCode">
這是我在我的控制器正在做:
function setDetectedLocation(location) {
$scope.info.countryCode = location.countryCode;
$scope.info.stateCode = location.stateCode;
$scope.info.city = location.city;
}
locationService.getLocation().then(setDetectedLocation, locationError);
當我手動填充選擇它時,它工作,如果我運行getLocation兩次,當國家的國家已經加載,它也可以。
任何指針?
我通過將控制器的'info.stateCode'從選擇'ngModel'中解除鏈接並觀察前者的變化,改善了情況。這將修復狀態列表的第一個負載,但當國家/地區選擇更改時問題仍然存在。 – jminuscula 2014-10-10 14:46:17