如何将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');
}
);
}
};
}]);
1}}我无法在hideCollectionForm()
内取得成功,因为它未定义。
答案 0 :(得分:3)
在控制器的顶部;
var self = this;
因此,self始终指向您的控制器以及您可以使用的承诺回调,
self.hideCollectionForm();