AngularJS, $http.get() and "controller as"

Doug picture Doug · May 14, 2015 · Viewed 9.1k times · Source

I'm pretty new to the whole AngularJS world and how it works, however I am struggling to get it working as expected. I know that its something to do with the way I am using $http.get() and trying to assign the variables back to my controller, but I just can't figure it out.

Using $scope instead of this I can get it working, however if possible, I'd prefer to be using this so I can use "controller as"

Code:

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

From this example, I cannot then access any results from the $http.get request from within the supplierList within the HTML page (i.e. {{ supplier.supplierList[0].supplier_name }} doesnt display any results)

I know that if I change the controller to $scope I can get access to that data (although not using the same format as above), and I also know the data is being populated by using console.log(this.supplierList) inside the .success call.

I also know that the reason its not working is because the context of this changes from within the controller to within the $http.get call.

So my question is this: How do you get access to the results from a $http.xxx call using this instead of scope? I have read a few different sources on it, but most talk about using $scope and promises. I've not found any that cover using this (or declaring it with var supplier = this). Any help would be much appreciated.

Thanks,

Answer

charlietfl picture charlietfl · May 14, 2015

Always store a variable reference to this so that you don't have context issues, then use that variable instead of this throughout controller

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