将此变量传递给angular $ http回调

时间:2016-08-05 12:11:18

标签: javascript angularjs

如何将this传递给角度$http then回调,以便我可以使用属性?没有$scope可以做到这一点吗? 这是我的代码:

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');
                   }
                );
    }
};

}]); hideCollectionForm()内取得成功,因为它未定义。

1 个答案:

答案 0 :(得分:3)

在控制器的顶部;

var self = this;

因此,self始终指向您的控制器以及您可以使用的承诺回调,

self.hideCollectionForm();