2015-06-06 2 views
0

Я должен загрузить файл на сервер ... У меня есть код в контроллере, но код можно использовать повторно. Поэтому я хотел бы переместить его на завод, а затем использовать фабрика каждый раз, когда мне это нужно ... Я не могу переместить этот код на завод. Если я его переведу, ничего не работает. Вот код, который я имею в моем контроллере и что я хотел бы перейти на заводе:Переместить код с контроллера на завод в угловом

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

I думаю, мне не нужно говорить о масштабах внутри фабрики ... и, возможно, слушатель должен быть внутри контроллера, даже если я предпочел бы, чтобы он оставался на заводе ... Может ли кто-нибудь мне помочь? спасибо

ответ

1

Правильно, вам не нужно $ scope на вашем заводе. Фабрика должна быть просто инструментом для вашего контроллера. Вот пример, основанный на вашем коде.

//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); 

    }); 
+0

нет способа разместить слушателя внутри фабрики? – Ciccio

+1

проблема в том, что фабрика в AngularJS не предназначена для этого. если вы хотите использовать прослушиватель в одном модуле - просто оставьте код обработки http в контроллере – shershen

+0

, есть способ переместить успех и провал за пределами фабрики, чтобы я мог управлять внутри контроллера? – Ciccio

1

$ scope: Контроллеры связаны с элементом в DOM и поэтому имеют доступ к области. Другие компоненты (например, службы) имеют доступ только к службе $ rootScope. (см. https://docs.angularjs.org/guide/di).

Вы можете использовать $ rootScope, но лучшим решением является изменение функции загрузки, чтобы принять массив файлов, и сделать наблюдателем fileSelected в контроллере или в директиве.

надеюсь, что это поможет!

+0

fileSelected - это событие, которое поднимает моя пользовательская директива ... нет способа управлять им внутри фабричной себя? – Ciccio

Смежные вопросы