【发布时间】:2015-08-12 04:12:56
【问题描述】:
我有一个“状态选择”指令,它使用基于国家代码的状态列表填充选择元素。该指令监视 countryCode 的更改以更新提供给 ng-options 的属性。
我现在正在尝试从我的控制器设置 model.countryCode 和 model.sateCode,但是当 countryCode 更改时填充状态选择,模型值会在选项有机会加载之前更新。
在我加载选项后,如何确保 select 确实选择了其 ng-model 中引用的选项?
这是我的指令:
.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中取消链接并观察前者的变化来稍微改善了这种情况。这修复了州列表的第一次加载,但是当国家选择改变时问题仍然存在。
标签: javascript angularjs angularjs-directive ng-options