2016-09-02 2 views
1

서비스를 사용하여 프록시 서버로 데이터를 전송하는 설정이 있습니다. 그것은 다음과 같습니다각도 지시문, 서비스 및 컨트롤러간에 데이터 공유

angular.module('app').service('apiService', ApiService); 

function ApiService($http) { 
    this.$http = $http; 
}; 

ApiService.prototype.uploadFile = function(fileContent) { 
    $.ajax({ 
     url: "/space_uploadFile/", 
     type: "POST", 
     dataType: "json", 
     data: { 
      fileContent: fileContent 
     }, 

     contentType: "application/json", 
     cache: false, 
     timeout: 5000, 
     complete: function() { 
      //called when complete 
      console.log('process complete'); 
     }, 
     success: function(data) { 
      console.log(data); 
      console.log('process success'); 
     }, 
     error: function() { 
      console.log('process error'); 
     }, 
     }); 
}; 

나는 이미지의 파일로드 및 자르기를 처리하는 지시어를 호출하고 다음

use strict'; 
angular 
    .module('app') 
    /** 
    * The ng-thumb directive 
    * @author: nerv 
    * @version: 0.1.2, 2014-01-09 
    */ 
    .directive('ngThumb', ['$window', 'apiService', function($window, apiService) { 
     var helper = { 
      support: !!($window.FileReader && $window.CanvasRenderingContext2D), 
      isFile: function(item) { 
       return angular.isObject(item) && item instanceof $window.File; 
      }, 
      isImage: function(file) { 
       var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; 
       return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; 
      } 
     }; 

     return { 
      restrict: 'A', 
      template: '<canvas/>', 
      link: function(scope, element, attributes) { 
       if (!helper.support) return; 

       var params = scope.$eval(attributes.ngThumb); 

       if (!helper.isFile(params.file)) return; 
       if (!helper.isImage(params.file)) return; 

       var canvas = element.find('canvas'); 
       var reader = new FileReader(); 

       reader.onload = onLoadFile; 
       reader.readAsDataURL(params.file); 


       function onLoadFile(event) { 
        var img = new Image(); 
        img.onload = onLoadImage; 
        img.src = event.target.result; 
       } 
       function uploadFile(imageData){ 
        var self = this; 
        apiService.uploadFile(imageData); 
       } 

       function onLoadImage() { 
        var width, height; 
        if (params.height>params.width) { 
         width=params.width*3; 
         height=width; 
        } else { 
         height = params.height*3; 
         width=height; 
        } 
        var maxWidth=600; 
        if (width<maxWidth) { 
         maxWidth=width; 
        } 
        //width = params.width || this.width/this.height * params.height; 

        canvas.attr({ width: width, height: height }); 
        canvas[0].getContext('2d').drawImage(this, 0, 0, maxWidth, maxWidth, 0,0, width, height); 
        //canvas[0].getContext('2d').drawImage(this, 0, 0, width, height); 
        var image = canvas[0].toDataURL(); 
        uploadFile(image); 
       } 
      } 
     }; 
    }]); 

지금은 Ajax 요청 (데이터 변수)에 의해 반환 된 데이터를 필요 내 컨트롤러

angular.module('app').controller('newProjectController', newProjectController); 


function newProjectController($rootScope, $scope, $location, apiService, FileUploader) { 
    this.apiService = apiService; 
    /*$scope.encoded = $base64.encode('a string'); 
    console.log($scope.encoded); 
    $scope.decoded = $base64.decode('YSBzdHJpbmc=');*/ 
    $rootScope.img=""; 

    var uploader = $scope.uploader = new FileUploader({ 
      url: '/space_uploadFile' 
     }); 

     // FILTERS 

     uploader.filters.push({ 
      name: 'imageFilter', 
      fn: function(item /*{File|FileLikeObject}*/, options) { 
       var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; 
       return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; 
      } 
     }); 
} 

에 전달 될 내 $rootScope 서비스에 주입 또는 지시에 Ajax 요청에서 데이터를 반환하거나하는 방법을 알아낼 수 없습니다. 다른 업로드의 경우 $http.get(...)을 사용하고 있지만 json으로 인코딩 된 base64 이미지를 사용하여이를 수행하는 방법을 알 수 없습니다.

누군가 내게 힌트를 줄 수 있습니까? 이미 감사드립니다!

업데이트 1 나는 Daniels 제안을 시도했습니다. 내 시계는 다음과 같습니다.

$scope.file=apiService.file; 

     $scope.$watch("apiService.file", function (newVal, oldVal, scope) { 
      console.log(newVal); 
      console.log("update"); 
     }); 

변수가 업데이트 될 때 문제가 발생하지만 문제가 발생하지 않습니다. 무엇이 잘못 되었나요?

+0

서비스, 일회성 통화 또는 ApiService에 대한 호출이 동적 일 수 있습니까? 일회성 호출 인 경우 컨트롤러가로드되기 전에 routeConfig에서이 호출을 해결할 수 있습니다. –

+0

서비스는 동적으로 – suMi

답변

2

응답을 서비스에 저장 한 다음 서비스를 주입하여 컨트롤러에서 응답 할 수 있습니다. 파일 변수에 감시자를 추가하여 변경된시기를 알 수 있습니다.

function ApiService($http) { 
    this.$http = $http; 
    this.file = {}; 
}; 

ApiService.prototype.uploadFile = function(fileContent) { 
    $.ajax({ 
    //... 
    success: function(data) { 
     this.file = data; 
    } 
    //... 
    }); 
}; 

또 다른 옵션은 $rootscope.$broadcast() 이벤트를 사용하여 컨트롤러에 드 responseData를 전송하는 것입니다.

+0

라고 불리우며 변수를 보는 방법의 예를 설명하거나 게시 할 수 있습니까? 나는 새로운 기능을 익히고 지금까지만 기본 기능을 사용했습니다. – suMi

+0

http://www.learn-angular.org/#!/lessons/watch – Amygdaloideum

+0

을보고 해결책이 될 것이라고 생각했던 코드를 업데이트했습니다. . 분명히 그렇지 않습니다. 어쩌면 당신을 도울 수 있습니까? – suMi

관련 문제