2015-10-26 85 views
0

我是新來Angular編寫指令,並跟隨文件上傳的egghead教程,並設法讓我的文件上傳工具與快遞/ multer一起工作。我有這個非常奇怪的行爲 - 雖然一旦文件被選中,那些醜陋的默認圖像之一顯示出來:圖片上傳指令角js

ugly alt image showing up--why?

當我點擊「上傳」一切都很好(除了當然的金卡戴珊):

enter image description here

這是我的角的代碼。我認爲一切都在服務器端工作正常:

控制器/指令:

angular.module('MyApp') 
    .controller('ProfileCtrl', function ($scope, $http, $rootScope, Profile) { 
    // $rootScope.currentUser = user; 
    $scope.user = $rootScope.currentUser; 
    $scope.name = $scope.user.name; 
    $scope.imageData = null; 
    $scope.pictures = $scope.user.facebook ? $scope.user.facebook.pictures : $scope.imageData; 

    // console.log($scope.user); 
    $scope.filesChanged = function (elm) { 
     $scope.files = elm.files; 
     $scope.apply(); 
    }; 

    $scope.upload = function() { 
     var fd = new FormData(); 
     angular.forEach($scope.files, function (file) { 
     fd.append('file', file); 
     }); 

     $http.post('upload', fd, { 
     transformRequest: angular.identity, 
     headers: { 
      'Content-Type': undefined 
     } 

     }).success(function (data) { 
     $scope.imageData = data; 
     console.log($scope.imageData); 
     }); 
    }; 
    }) 
    .directive('fileInput', ['$parse', 
    function ($parse) { 
     return { 
     restrict: 'A', 
     link: function (scope, elm, attrs) { 
      elm.bind('change', function() { 
      $parse(attrs.fileInput) 
       .assign(scope, elm[0].files); 
      scope.$apply(); 
      }); 
     } 
     }; 
    } 
    ]); 

HTML:

<center> 
    <h3>Your Profile</h3> 
</center> 
<h4 class="col-sm-2 sidebar">{{name}} </h4> 
<div class="col sm-2 col-sm-offset-2 sidebar" ng-if="user.facebook"> 
    <img data-ng-src="{{pictures}}"> 
</div> 
<div> 

    <br> Change Your Profile Picture: 
    <br> 
    <form ng-controller="ProfileCtrl"> 
     <input type="file" file-input="files" multiple /> 
     <button ng-click="upload()">Upload</button> 
     <li ng-repeat="file in files">{{file.name}} 
     <img src="data:image/png;base64,{{imageData}}"> 
     <button ng-click="saveImage()"> 
      Save New Profile Picture 
     </button> 
     </li> 
    </form> 
</div> 

除了這個具體問題,我沒有在高抓級別指令的目的是什麼。爲什麼我不能只重複使用multer中'/ upload'路由返回的數據?

UPDATE:

感謝@jontewks,我想通了。出於某種原因,我宣佈$scope.imageData = null

在我的控制器的頂部。一旦我刪除它的工作!

回答

1

圖片直到您點擊上傳才顯示的原因是,它正在$ scope上查找{{imageData}},但直到http.post的.success發生時纔可用。在上傳之前查看是否有辦法使用文件數據,這將解決問題。