Angularjs 在API响应之前调用ng init

Angularjs 在API响应之前调用ng init,angularjs,Angularjs,我在控制器中有这样的功能 this.getStates = function () { LoadingService.enableLoading(); CartService.getStates(self.customerDetails.Country).then(function (response) { response = response.data;

我在控制器中有这样的功能

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>

其中self.customerDetails.Country作为对象出现

ng init只对表达式求值一次。在您的情况下,因为您的请求是异步的,所以当您的请求成功时,已经计算了ng init。初始化变量的更好方法是将其写入成功回调中

checkoutCntrl.customerDetails.Country = checkoutCntrl.countries[107];

如果您不希望您的选择显示在请求之前,请考虑使用NG如果仅在满足条件时才呈现指令。比如说

<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();
            });
内容。。。
CartService.getStates(self.customerDetails.Country)。然后(函数(响应){
response=response.data;
self.states=response.State;
$scope.showMeOnSuccessfulRequest=true;
LoadingService.disableLoading();
}).catch(函数(响应){
控制台日志(响应);
LoadingService.disableLoading();
});

请帮助显示您的模板代码。如果我这样做,它将设置值,但当我尝试进入时,它将作为对象而不是值出现。如果我选择了其他选项,那么它只是发送值而不是对象。还有一个问题是,如果在从控制器中选择其他选项后,它将选择空选项。您可以简要介绍您正在工作的场景,以便我提供正确的示例,这将帮助您更好地理解它。对于我来说,选择数据来自服务器,默认值选择为INDIA。并且需要调用另一个API来获取印度各州。现在,您的解决方案正在选择印度,然后在手动更改“选择”后,无论我选择什么,都会选择“空白”
<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();
            });