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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@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.
@pkyo - found it, I updated my answer to include it at the end.
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() {}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.