AngularJS,$ http.get()和"控制器为"

Dou*_*oug 7 javascript angularjs angularjs-http

我对整个AngularJS世界以及它是如何工作都很陌生,但是我很难让它按预期工作.我知道它与我使用的方式有关,$http.get()并试图将变量分配回我的控制器,但我无法弄明白.

使用$scope而不是this我可以使它工作,但如果可能的话,我更喜欢使用this所以我可以使用"控制器作为"

码:

app.controller('ctrlSuppliers', function($http){

    this.supplierList = {};

    $http.get("http://some_url_here")
            .success(function(response) {  this.supplierList = response.records;})
            .error(function() { this.supplierList = [{supplier_id: 0, supplier_name: 'Error Getting  Details'}];});
});
Run Code Online (Sandbox Code Playgroud)

从这个例子中,我无法$http.getsupplierListHTML页面内部访问请求中的{{ supplier.supplierList[0].supplier_name }}任何结果(即不显示任何结果)

我知道如果我将控制器更改为$scope可以访问该数据(虽然不使用与上面相同的格式),并且我也知道通过console.log(this.supplierList).success调用中使用来填充数据.

我也知道它不工作的原因是因为this从控制器内到$http.get调用内的变化的上下文.

所以我的问题是:如何使用this而不是使用$ http.xxx调用来访问结果scope?我已经阅读了一些不同的消息来源,但大多数人都在谈论使用$scope和承诺.我没有发现任何封面使用this(或声明它var supplier = this).任何帮助将非常感激.

谢谢,

cha*_*tfl 9

始终存储变量引用,this以便您没有上下文问题,然后使用该变量而不是this整个控制器

app.controller('ctrlSuppliers', function($http){
    var vm = this;
    // now can forget using "this" and use variable instead
    vm.supplierList = {};

    $http.get("http://some_url_here") .success(function(response) {
         // no context issues since "vm" is in scope  
         vm.supplierList = response.records;
    });               
});
Run Code Online (Sandbox Code Playgroud)