pkyo pkyo - 13 days ago 7
AngularJS Question

Cannot access a controller function inside $http.get method

This is my controller:

var app = angular.module('myApp', [ 'ngMaterial' ]);
app.controller('searchController',['$scope','$http',function($scope,$http) {
this.selectedItemChange = function(item) {
$http.get("url")
.then(function(response){
this.initializeProfiles();
});
}
this.initializeProfiles = function() {}
}


But I am getting the error
TypeError: this.initializeProfiles is not a function
.

How do I access initializeProfiles inside the .then of $http.get.

Answer

You need a reference to the control from inside the callback, create one before you execute the call to the http.get.

var app = angular.module('myApp', [ 'ngMaterial' ]);
app.controller('searchController',['$scope','$http',function($scope,$http) {
    this.selectedItemChange = function(item) {
    var me = this; // me = this
    $http.get("url")
        .then(function(response){
            me.initializeProfiles(); // me
    });
    }
    this.initializeProfiles = function() {}
}

See this excelent SO answer for a guide to how this is defined in javascript: How does the "this" keyword in Javascript act within an object literal?.