Javascript 异步为控制器变量赋值-AngularJS
我通过Javascript 异步为控制器变量赋值-AngularJS,javascript,angularjs,asynchronous,promise,Javascript,Angularjs,Asynchronous,Promise,我通过companiesData.getCompanies()从远程请求获取数据,并将其放入控制器变量中 控制器不会等待承诺解析,将响应数组设置为空 JS控制器: angular.module('X.Exh', []) .controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) { this.companies = []; companiesData.ge
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
});
});
<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 -->
HTML:
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
});
});
<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.companys
数字为空。(当然,如果我没有在控制器的开头执行this.companys=[];
,我的HTML会说Exh.companys
是未定义的
如何正确获取数据?未命名函数中的此项不会影响原始的
此项。公司
:
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
时运行
或者,您只需访问$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.
});
});
使用$scope.companies=[];非常感谢,你是对的!但实际上我使用了var self=this;然后是self.companys。这是一个很好的解决方案?
var self=this;
与var vm=this;
相同,所以唯一的限制是将ng controller='exhibitorsconner'声明为Exh'
,并访问html中的数据,如Exh.myvar
我们已经实现了第二个解决方案,这也是大型应用程序的最佳实践,所以它是“ok”。