在 angular 中将一些代码从控制器移动到工厂

Move some code from controller to factory in angular

我必须将一些文件上传到服务器...我的控制器中有一些代码,但代码是可重用的..所以我想将它移到工厂中,然后在每次需要时使用该工厂。 ..我无法将此代码移至工厂..如果我移动它,则不再起作用。这是我控制器中的代码,我想在工厂中移动:

public_area.controller("SeguiAttivazioneController", function ($scope, SeguiAttivazioneService) {
    ...

    //an array of files selected
    $scope.files = [];

    //listen for the file selected event
    $scope.$on("fileSelected", function (event, args) {
        $scope.$apply(function () {
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
        });
    });

    //the save method
    $scope.save = function () {
        $http({
            method: 'POST',
            url: "/api/Upload",
            headers: { 'Content-Type': undefined },
            //This method will allow us to change how the data is sent up to the server
            // for which we'll need to encapsulate the model data in 'FormData'
            transformRequest: function (data) {
                var formData = new FormData();
                //need to convert our json object to a string version of json otherwise
                // the browser will do a 'toString()' on the object which will result 
                // in the value '[Object object]' on the server.
                formData.append("model", angular.toJson(data.model));
                //now add all of the assigned files
                for (var i = 0; i < data.files.length; i++) {
                    //add each file to the form data and iteratively name them
                    formData.append("file" + i, data.files[i]);
                }
                return formData;
            },
            //Create an object that contains the model and files which will be transformed
            // in the above transformRequest method
            data: { model: $scope.model, files: $scope.files }
        }).
        success(function (data, status, headers, config) {
            alert("success!");
        }).
        error(function (data, status, headers, config) {
            alert("failed!");
        });
    };
});

我试过这样的:

var public_area = angular.module("public-area");

public_area
.factory("uploadFactory", function ($scope, $http) {
        //an array of files selected
        $scope.files = [];

        //listen for the file selected event
        $scope.$on("fileSelected", function (event, args) {
            $scope.$apply(function () {
                //add the file object to the scope's files collection
                $scope.files.push(args.file);
            });
        });

       return {
           // upload: $resource("/api/EasyPay/")
           upload: function () {
               $http({
                   method: 'POST',
                   url: "/api/Upload",
                   headers: { 'Content-Type': undefined },
                   //This method will allow us to change how the data is sent up to the server
                   // for which we'll need to encapsulate the model data in 'FormData'
                   transformRequest: function (data) {
                       var formData = new FormData();
                       //need to convert our json object to a string version of json otherwise
                       // the browser will do a 'toString()' on the object which will result 
                       // in the value '[Object object]' on the server.
                       formData.append("model", angular.toJson(data.model));
                       //now add all of the assigned files
                       for (var i = 0; i < data.files.length; i++) {
                           //add each file to the form data and iteratively name them
                           formData.append("file" + i, data.files[i]);
                       }
                       return formData;
                   },
                   //Create an object that contains the model and files which will be transformed
                   // in the above transformRequest method
                   data: { model: $scope.model, files: $scope.files }
               }).
               success(function (data, status, headers, config) {
                   alert("success!");
               }).
               error(function (data, status, headers, config) {
                   alert("failed!");
               });
           }
       };
   });

但是我有这个error

我想我不必说工厂内部的作用域......也许监听器必须在控制器内部,即使我更希望它留在工厂...... 谁能帮帮我吗? 谢谢

$scope:控制器与 DOM 中的元素相关联,因此可以访问范围。其他组件(如服务)只能访问 $rootScope 服务。(参见 https://docs.angularjs.org/guide/di)。

您可以使用$rootScope,但最好的解决方案是更改上传功能以接受文件数组,并在控制器或指令中设置fileSelected 的观察者。

希望对您有所帮助!

没错,您的工厂中不需要 $scope。 Factory 应该只是你控制器的一个工具箱。这是一个基于您的代码的示例。

//factory
.factory("uploadFactory", function ($http) {
       return {
           // upload: $resource("/api/EasyPay/")
           upload: function (data) {
               $http({
                   method: 'POST',
                   url: "/api/Upload",
                   headers: { 'Content-Type': undefined },
                  //some transformations....
                   data: { model: data.model, files: data.files }
               }).
               success(function (data, status, headers, config) {
                   alert("success!");
               }).
               error(function (data, status, headers, config) {
                   alert("failed!");
               });
           }
       };
   });

//controller
.controller("SeguiAttivazioneController", function ($scope, SeguiAttivazioneService, uploadFactory) {
    ...

    //an array of files selected
    $scope.files = [];

    //listen for the file selected event
    $scope.$on("fileSelected", function (event, args) {
        $scope.$apply(function () {
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
        });

//call factory with $scope.files as 'data' argument
uploadFactory.upload($scope.files);

    });