AngularJS 工厂函数未定义

AngularJS factory function undefined

过去 3 个小时我一直在研究这个问题,我非常困惑。 apache2 错误日志说 php 脚本正在 运行,但是当它被调用时我从我的工厂收到一个错误。

TypeError: InputUpload.uploadImage(...) is undefined

当 firefox 调试器说它未定义时,我不明白 javascript 是如何达到 运行 php 脚本...

var app = angular.module("app", ["ui.bootstrap"]);

//
app.factory("API", function ($http) {
    return {
    uploadImage: function (image) {
        $http.post('/js/upload_image.php', image);
    }
    }
});

app.controller("MainController", ['$scope', '$http', 'API', function($scope, $http, 'API') {
    $scope.imageUrl = "";

    $scope.template = "";

    $scope.templates = [];

    $scope.templates.push("select an option...");
    $scope.templates.push("MakeGray");
    $scope.templates.push("Canny");

    $scope.template = $scope.templates[0];

    $scope.add = function() {
    alert("HELLO");
    var f = document.getElementById('file').files[0];
    var r = new FileReader();
    r.onloadend = function(e) {
        var data = e.target.result;

        API.uploadImage(data)
        .success(function (imgUrl) {
            $scope.imageUrl = imgUrl;
        })
        .error (function (error) {
        });
    }

    r.readAsBinaryString(f);
    }
});

试试这个

    app.controller("MainController", ['$scope', '$http', 'InputUpload', 'API', function($scope, $http, API) {
//your code here..........

您需要 return $http 承诺 :

app.factory("API", function ($http) {
    return {
        uploadImage: function (image) {
           //add return her 
           return $http.post('/js/upload_image.php', image);
        }
    }
});

您的问题出在控制器注入中。

在您的控制器中将其替换为

.controller("MainController", ['$scope', '$http', 'API', function($scope, $http, API) {

然后调用你的函数 API.uploadImage(img)