Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS-组件中的异步绑定_Angularjs - Fatal编程技术网

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