角度误差:$ http.post不是函数

时间:2017-07-11 15:30:23

标签: javascript angularjs

我试图在我的服务器上发布文件,因为它会被直接连接,所以我做了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)
                    });
                });
            });
        }
    };
}

1 个答案:

答案 0 :(得分:3)

$http功能中删除link。它不需要

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:您还需要从$http回调中移除$apply。您不需要将$ http传递给任何其他内部函数。它已经注入并可用于所有其他内部方法。

scope.$apply(function(){}