1

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?

Evans Murithi
  • 2,847
  • 1
  • 19
  • 26
pkyo
  • 144
  • 11

2 Answers2

3

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?.

Community
  • 1
  • 1
Igor
  • 55,253
  • 10
  • 80
  • 149
  • @pkyo - it has to do with `this`, the reference changes depending on the call stack and is not implicitly captured in a callback. There is a very good SO answer explaining all the details of `this`, give me a minute and I will find it. – Igor Nov 23 '16 at 11:23
  • @pkyo - found it, I updated my answer to include it at the end. – Igor Nov 23 '16 at 11:30
0
  var app = angular.module('myApp', [ 'ngMaterial' ]);
  app.controller('searchController',['$scope','$http',function($scope,$http) {
   var vm = this;
  vm.selectedItemChange = function(item) {
  $http.get("url")
    .then(function(response){
        vm.initializeProfiles();
   });
}
   vm.initializeProfiles = function() {}
}