0

I cannot pass/set the value to the text-area outside the controller. I am uploading an excel and regarding the upload status I want to set some data to a text-area. This is my code so far:

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);
    };
}]);
1
  • Also, you should be using .then instead of .success and .error callbacks. If I am right, they have been deprecated now. Read Angular $http API for more Commented Jul 31, 2016 at 11:28

1 Answer 1

1

This typically seems a case where you should be using promises. From your services you should return a promise and based on their resolution or rejection, you should bind the variable on controller.

your service should look something like:

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}
        })
    }
}]);

Since, http itself return a promise, you can directly return it, instead of making your custom promise.

and your controller should be like:

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(){

}
    };
}]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.