DJack
DJack

Reputation: 639

Angular - pass scope to service and set value

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

Upvotes: 0

Views: 60

Answers (1)

Saurabh Tiwari
Saurabh Tiwari

Reputation: 5131

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

}
    };
}]);

Upvotes: 1

Related Questions