赋值给变量控制器asyncronously - AngularJS [英] Assign value to controller variable asyncronously - AngularJS

查看:140
本文介绍了赋值给变量控制器asyncronously - AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 companiesData.getCompanies从远程请求数据(),放入控制器变量。

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控制器:

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 是不确定的。

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?

推荐答案

这无名函数内部不影响原 this.companies

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.
    });
});

注意虚拟机。当你使用运行 controllerAs 格式

另外,您可以只需访问 $范围变量:

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.
    });
});

这篇关于赋值给变量控制器asyncronously - AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆