2

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.

im_tsm
  • 1,965
  • 17
  • 29

1 Answers1

3

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();
scokmen
  • 571
  • 3
  • 19