Angular - 将范围传递给服务和设置值

时间:2016-07-31 11:12:56

标签: angularjs

我无法将值传递/设置到控制器外部的文本区域。 我正在上传一个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);
    };
}]);

1 个答案:

答案 0 :(得分:1)

这通常是您应该使用promises的情况。 从您的服务中,您应该返回一个承诺,并根据其解决或拒绝,您应该将变量绑定在控制器上。

您的服务应该类似于:

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

}
    };
}]);