gpt4 book ai didi

javascript - Angular 错误 : $http. 帖子不是函数

转载 作者:行者123 更新时间:2023-11-28 17:53:08 25 4
gpt4 key购买 nike

我试图在文件附加到directve后立即将其发布到我的服务器上,因此我进行了api调用,但在执行时遇到了此错误。我不知道我哪里出错了

这是我的代码

app.directive('fileModel',fileupload);

fileupload.$inject = ['$http','$parse'];

function fileupload ($http,$parse) {
return {
restrict: 'A',
link: function(scope, element, attrs,$http) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;

element.bind('change', function(){
scope.$apply(function($http){
modelSetter(scope, element[0].files[0]);
var fd = new FormData();
fd.append('file', element[0].files[0]);
fd.append('id', user_id);
var uploadUrl = "https://******/routes/contactRoute.php?action=upload";
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response)
});
});
});
}
};
}

最佳答案

link 函数中删除 $http。不需要

app.directive('fileModel',fileupload);

fileupload.$inject = ['$http','$parse'];

function fileupload ($http,$parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;

element.bind('change', function(){
scope.$apply(function($http){
modelSetter(scope, element[0].files[0]);
var fd = new FormData();
fd.append('file', element[0].files[0]);
fd.append('id', user_id);
var uploadUrl = "https://******/routes/contactRoute.php?action=upload";
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response)
});
});
});
}
};
}

编辑 1:您还需要从 $apply 回调中删除 $http。您不需要将 $http 传递给任何其他内部函数。它已经被注入(inject)并可用于所有其他内部方法。

scope.$apply(function(){}

关于javascript - Angular 错误 : $http. 帖子不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com