Assign value to controller variable asyncronously

2019-07-30 19:00发布

I get data from remote request by companiesData.getCompanies() and put it into controller variable.

The controller does not wait for promise resolution, figuring the response array empty.

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 -->

Not waiting for the HTTP request, Exh.companies figures empty. (of course if I don't do this.companies = []; at the beginning of my controller, my HTML says that Exh.companies is undefined.

How do I get data properly?

1条回答
ら.Afraid
2楼-- · 2019-07-30 19:49

this inside the unnamed function does not influence original 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.
    });
});

Please note that vm. runs when you use controllerAs pattern.

Alternatively you can simply access $scope variable:

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.
    });
});
查看更多
登录 后发表回答