如何在angularJS

时间:2017-10-30 19:04:52

标签: angularjs file

我希望在UI上显示文件上传成功或失败的消息。 我有以下文件结构。

控制器:

我的文件上传功能如下:

       $scope.uploadFile = function () {
                   //using a service
                   fileUpload.uploadFileToUrl(file, uploadUrl)
    };

这完全没问题。 fileUpload服务如下所示:

       angular.module('myApp').service('fileUpload', ['$http', function  
     ($http) {


      //upload function happens here and returns a promise, This is     executing fine.
            .success(function (response) {
                if (response.status=="uploadSuccess")
                {
                    alert("The file has been successfully uploaded");
                    var message = "success";
                                        }
                if (response.status == "uploadFailure") {
                    alert("The file could not be uploaded");

                                      }
                if (response.status == "uploadFailureExc") {
                    alert("The file could not be uploaded due to an exception that occured");


                }
                if (response.status == "FileExists") {
                    alert("The file could not be uploaded - a file with that name already exists");

                                        }


            })
            .error(function () {

            });

    }
      }]);

如何在html页面上显示消息而不是使用警报。我试图设置变量var消息。然后将它退出服务,但它进入一个无限循环并陷入困境。我试图使用范围变量,它也会进入一些无限循环。

帮助

2 个答案:

答案 0 :(得分:1)

当响应可用时,

$http将异步触发回调。 您可以使用.then从服务中获取回复

.then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
 }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
 });

并在您的控制器中

fileUpload.uploadFileToUrl(file, uploadUrl).then(function(data) {
    console.log(data);
});

答案 1 :(得分:0)

.success(function (response) {
       if (response.status=="uploadSuccess")
       {
           var message = "The file has been successfully uploaded";
           return message;
    }
       if (response.status == "uploadFailure") {
           var message = "The file could not be uploaded";
           return message;
                             }
       if (response.status == "uploadFailureExc") {
           var message = "The file could not be uploaded due to an exception that occured";
           return message;

       }
       if (response.status == "FileExists") {
           var message = "The file could not be uploaded - a file with that name already exists";
           return message;

                               }


   })

使用此代码替换on success block,该代码在上传时为每个条件返回一条消息,现在您可以在控制器中以任何方式使用它。希望这有帮助。!