2016-07-31 60 views
0

我無法將值傳遞/設置到控制器外部的文本區域。 我上傳一個excel,關於上傳狀態,我想將一些數據設置爲文本區域。 這是我到目前爲止的代碼:角度 - 通過範圍服務和設置值

app.service('fileUpload', ['$http', function ($http) { 
    this.uploadFileToUrl = function(file, uploadUrl, commentArea){ 
     var fd = new FormData(); 
     fd.append('file', file); 
     $http.post(uploadUrl, fd, { 
      transformRequest: angular.identity, 
      headers: {'Content-Type': undefined} 
     }) 
     .success(function(){ 
/*   commentArea.append('This is not working'); 
      commentArea = 'This is not working'; 
      $scope.outputImportObject = 'This is not working'; 
*/ 
      alert('The file was succesfully uploaded!'); 
     }) 
     .error(function(){ 
      alert('There was an error while inserting the file!'); 
    }); 
    } 
}]); 

app.controller('UploadCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){ 
    $scope.uploadFile = function(){ 
     $scope.outputImportObject = 'This is working'; 

     var file = $scope.myFile; 
     var commentArea = $scope.outputImportObject; 
     fileUpload.uploadFileToUrl(file, ws_url+'upload_excel.php',commentArea); 
    }; 
}]); 
+0

此外,你應該使用的。那麼代替.success和.error回調。如果我是對的,他們現在已經被棄用了。閱讀更多的Angular'$ http' API –

回答

1

這通常看來,你應該使用承諾的情形。 從你的服務你應該返回一個承諾,並根據他們的決議或拒絕,你應該綁定控制器上的變量。

您的服務應該是這個樣子:

app.service('fileUpload', ['$http', function ($http) { 
    this.uploadFileToUrl = function(file, uploadUrl, commentArea){ 
     var fd = new FormData(); 
     fd.append('file', file); 
     return 
     $http.post(uploadUrl, fd, { 
      transformRequest: angular.identity, 
      headers: {'Content-Type': undefined} 
     }) 
    } 
}]); 

,因爲HTTP本身返回一個承諾,你可以直接返回,而不是使您的自定義它的承諾,。

和控制器應該是這樣的:

app.controller('UploadCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){ 
    $scope.uploadFile = function(){ 
     $scope.outputImportObject = 'This is working'; 

     var file = $scope.myFile; 
     var commentArea = $scope.outputImportObject; 
     fileUpload.uploadFileToUrl(file, ws_url+'upload_excel.php',commentArea) 
.then(doThisOnSuccess, doThisOnFailure); 

function doThisOnSuccess(){ 

code for binding to text area should go here 
} 

function doThisOnFailure(){ 

} 
    }; 
}]);