我在控制器中有这样的功能
this.getStates = function () {
LoadingService.enableLoading();
CartService.getStates(self.customerDetails.Country).then(function (response) {
response = response.data;
self.states = response.State;
LoadingService.disableLoading();
}).catch(function (response) {
console.log(response);
LoadingService.disableLoading();
});
};
在我看来它以这种方式呈现
这是模板代码
<select required id='country' class="form-control" ng-model="checkoutCntrl.customerDetails.Country" ng-init="checkoutCntrl.customerDetails.Country = checkoutCntrl.countries[107]"
ng-options="item.CountryCode as item.CountryName for item in checkoutCntrl.countries track by item.CountryCode"
ng-select="checkoutCntrl.getStates()" ng-change="checkoutCntrl.getStates()">
</select>
我想选择默认国家/地区,如何选择它。我在使用ng-init中的函数时,在从服务器获取数据之前调用它
此处是设置国家/地区值以尝试获取状态后的下一个代码
this.getStates = function () {
console.log('obj=====>');
console.log(self.customerDetails.Country.CountryCode);
LoadingService.enableLoading();
CartService.getStates(self.customerDetails.Country).then(function (response) {
response = response.data;
self.states = response.State;
LoadingService.disableLoading();
}).catch(function (response) {
console.log(response);
LoadingService.disableLoading();
});
};
其中self.customerDetails.Country将作为对象出现
答案 0 :(得分:0)
ng-init仅对表达式求值一次。在您的情况下,由于您的请求是异步的,因此在您的请求成功时,已经评估了ng-init。初始化变量的更好方法是在成功回调
中写入此内容checkoutCntrl.customerDetails.Country = checkoutCntrl.countries[107];
如果您不希望在请求之前显示您的选择,请考虑使用ng-if仅在满足条件时呈现指令。例如
<div ng-if="showMeOnSuccessfulRequest" >Content...</div>
CartService.getStates(self.customerDetails.Country).then(function (response) {
response = response.data;
self.states = response.State;
$scope.showMeOnSuccessfulRequest = true;
LoadingService.disableLoading();
}).catch(function (response) {
console.log(response);
LoadingService.disableLoading();
});