我通过 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/