问题描述
我用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!