Tuhin Subhra Mandal Tuhin Subhra Mandal - 3 months ago 10
AngularJS Question

Pass this variable to angular $http callback

How can I pass

this
to angular
$http then
callback, so that I can use properties? Is it possible to do that without
$scope
?
Here is my code:

angular.module('app').controller('CollectionCtrl',['$http','$scope', function ($http, $scope) {
this.formVisible = false;
this.showCollectionForm = function () {
this.formVisible = true;
};
this.hideCollectionForm = function () {
this.formVisible = false;
};
// New Collection Add
this.collection_name = '';
this.collection_text = '';
this.collection_nameError = false;
this.addCollection = function () {
if (this.collection_name === '') {
this.collection_nameError = true;
}
else {
this.collection_nameError = false;
var url = ROOT_URL + "api/post-image";
var data = {
'collection_name' : this.collection_name,
'collection_text' : this.collection_text
}
$http.post(url, data)
.then(
function(response){
this.hideCollectionForm();
$scope.fetchUserCollection();
},
function(response){
console.log('failure callback');
}
);
}
};


}]);
I am unable to call
hideCollectionForm()
inside
then
success because it is undefined.

Answer

On the top of the controller;

var self = this;

So self is always refers to the your controller and in the promise callback you ca use as,

self.hideCollectionForm();
Comments