异步为控制器变量赋值 - AngularJS

时间:2016-06-30 12:43:09

标签: javascript angularjs asynchronous promise

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

控制器不等待承诺解析,将响应数组清空。

JS控制器:

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数字为空。 (当然,如果我在控制器的开头没有this.companies = [];,我的HTML会说Exh.companies未定义。

如何正确获取数据?

1 个答案:

答案 0 :(得分:3)

这个未命名的函数内部不影响原始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.
    });
});