将一些代码从控制器移动到工厂角

时间:2015-06-06 07:19:29

标签: angularjs controller factory

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

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

我想我不必说工厂里面的范围......也许听众必须在控制器里面,即使我希望它留在工厂...... 有人可以帮我吗? 谢谢

2 个答案:

答案 0 :(得分:1)

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

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

希望这有帮助!

答案 1 :(得分:1)

这是对的,你的工厂不需要$ scope。工厂应该只是控制器的工具箱。以下是基于您的代码的示例。

{{1}}