AngularJS-组件中的异步绑定
您好,我有这个组件:AngularJS-组件中的异步绑定,angularjs,Angularjs,您好,我有这个组件: zpc.component("myComponent", { template: '<button ng-click="$ctrl.find()">CLICK</button>\ {{$ctrl.results|json}}\ //allways empty </div>', controller: function MyComponent($http) { this.tex
zpc.component("myComponent", {
template: '<button ng-click="$ctrl.find()">CLICK</button>\
{{$ctrl.results|json}}\ //allways empty
</div>',
controller: function MyComponent($http) {
this.text = "";
this.results = [];
this.find = function () {
$http.get("https://swapi.co/api/films/1").then(function (response) {
this.results = response.data;
console.log(this.results); //here is data
});
}
}
});
zpc.component(“myComponent”{
模板:'单击\
{{$ctrl.results | json}\//始终为空
',
控制器:函数MyComponent($http){
this.text=“”;
这个结果=[];
this.find=函数(){
$http.get(“https://swapi.co/api/films/1)然后(函数(响应){
this.results=response.data;
console.log(this.results);//这里是数据
});
}
}
});
单击后,数据已正确加载,但不会显示在视图中。如何从异步将数据绑定到视图?谢谢。您需要将回调函数绑定到此:
$http.get("https://swapi.co/api/films/1").then(function (response) {
this.results = response.data;
console.log(this.results); //here is data
}.bind(this));
或者避免使用这个,而是使用它
var vm = this;
vm.find = function () {
$http.get("https://swapi.co/api/films/1").then(function (response) {
vm.results = response.data;
console.log(vm.results); //here is data
});
}