javascript - 异步地为 Controller 变量赋值 - AngularJS

标签 javascript angularjs asynchronous promise

我通过 companiesData.getCompanies() 从远程请求中获取数据,并将其放入 Controller 变量中。

Controller 不等待 promise 解析,认为响应数组为空。

JS Controller :

angular.module('X.Exh', [])

.controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) {

    this.companies = [];

    companiesData.getCompanies().then(function(response) {
        this.companies = response.data;
console.log(this.companies); // working very well
    });
});

HTML:

 <ion-alpha-scroll ng-model="Exh.companies" key="name" display-key="name" subheader="true" use-complete-alphabet="true">
<!-- Basically the ion alpha scroll is just doing a ng-repeat for every item, it is not the problem here -->

不等待 HTTP 请求,Exh.companies 数字为空。 (当然,如果我不在 Controller 的开头执行 this.companies = [];,我的 HTML 会说 Exh.companies 未定义。

如何正确获取数据?

最佳答案

未命名函数中的 this 不影响原始 this.companies:

angular
 .module('X.Exh', [])
 .controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) {

    var vm = this;
    vm.companies = []; // you can omit this but for documentation and code clear you can declare it;

    companiesData.getCompanies().then(function(response) {
        vm.companies = response.data;
        console.log(vm.companies); // does not point to local this.companies but to the caller context.
    });
});

注意 vm. 在您使用controllerAs 时运行 pattern .

或者,您可以简单地访问 $scope 变量:

angular
 .module('X.Exh', [])
 .controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) {

    $scope.companies = []; // you can omit this but for documentation and code clear you can declare it;

    companiesData.getCompanies().then(function(response) {
        $scope.companies = response.data;
        console.log($scope.companies); // does not point to local this.companies but to the caller context.
    });
});

关于javascript - 异步地为 Controller 变量赋值 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38123466/

相关文章:

javascript - 如何通过拖动另一张图像来更改图像?

javascript - 加载外部图像之前检查浏览器缓存

javascript - NodeJS 不会导入非 NodeJS 文件

javascript - 如何在html中获取用户输入并将其设置为js中的变量?

c# - 同时执行所有任务并等待它们完成?

AngularJS:无法更改输入类型

javascript - Angular.JS onclick 函数只在第一次点击时调用

angularjs - Safari 和 IE 的 File() 构造函数是否有替代方法?

python - Quamash 和 PyQt5 - 进程结束时出现额外窗口

c++ - 在一个线程中完成的操作对另一个线程可见,而无需显式同步