19

我是 AngularJS 的新手,并试图找到如何在数据加载时显示等待消息的方法?我的意思是数据开始加载,显示消息并在数据加载完成后将其删除。

我已经搜索了互联网,但没有找到我需要的任何东西......

4

5 回答 5

46
<div ng-if="data.dataLoading">
    Loading...
</div>

JS

$scope.data.dataLoading = true;

return someService.getData().then(function (results) {                    
    ...
}).finally(function () {
    $scope.data.dataLoading = false;
});
于 2013-08-21T13:16:36.993 回答
5

取决于您从哪里加载数据。我使用的一种解决方案是创建一个 LoadingService

app.factory('LoadingService', function($rootScope) {
    return {
        loading : function(message) {
             $rootScope.loadingMessage = message;
        },
        loaded : function() {
             $rootScope.loadingMessage = null;
        }
    }
}).controller('FooController', function($scope,$http,LoadingService) {

   $scope.loadSomeData = function() {
       LoadingService.loading('Data is loading');

       $http.get('/data').finally(function() {
            LoadingService.loaded();
       });
   };
});

因为我只有一个显示消息的地方,所以我可以使用 RootScope 来处理这个问题。如果您想多次收到加载消息,您也可以编写一个指令来处理这个问题,就像 Codezilla 发布的那样

于 2013-08-21T13:34:14.300 回答
1

编辑:不适用于版本 1.3.0 。使用请求/响应拦截器。

如果您想在全局范围内侦听所有请求并在有请求待处理时显示加载小部件,您可以使用请求/响应转换器计算请求。您只需添加一个计数器并在新请求时增加并在响应时减少它。我为此使用了提供者:

$httpProvider
  .defaults
  .transformRequest
  .push(function(data) {
      requestNotificationProvider
      .fireRequestStarted(data);
      return data;
});

对于transformResponse. 然后同一个提供者保存有关有多少请求待处理的信息,您可以在指令中使用它们。您可以在此处阅读(并复制/粘贴代码)完整的博客文章: http : //www.kvetis.com/2014/01/angularjs-loading-widget.html 附有一个工作演示。

于 2014-01-16T16:51:43.747 回答
1

我已经在这篇 StackOverflow 文章中回答了这个问题,但这里是对我所做工作的回顾。

如果您正确设置代码样式,并确保对 Web 服务的所有调用都通过一个特定factory函数,那么您可以使该factory函数句柄显示和隐藏“请稍候”弹出窗口。

这是factory我用来调用所有 GET Web 服务的函数:

myApp.factory('httpGetFactory', function ($http, $q) {
    return function (scope, URL) {
        //  This Factory method calls a GET web service, and displays a modal error message if something goes wrong.
        scope.$broadcast('app-start-loading');          //  Show the "Please wait" popup

        return $http({
            url: URL,
            method: "GET",
            headers: { 'Content-Type': undefined }
        }).then(function (response) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup
            if (typeof response.data === 'object') {
                return response.data;
            } else {
                // invalid response
                return $q.reject(response.data);
            }
        }, function (errorResponse) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup

            //  The WCF Web Service returned an error.  
            //  Let's display the HTTP Status Code, and any statusText which it returned.
            var HTTPErrorNumber = (errorResponse.status == 500) ? "" : "HTTP status code: " + errorResponse.status + "\r\n";
            var HTTPErrorStatusText = errorResponse.statusText;

            var message = HTTPErrorNumber + HTTPErrorStatusText;

            BootstrapDialog.show({
                title: 'Error',
                message: message,
                buttons: [{
                    label: 'OK',
                    action: function (dialog) {
                        dialog.close();
                    },
                    draggable: true
                }]
            });

            return $q.reject(errorResponse.data);
        });
    };
});

这将被称为:

myApp.webServicesURL = "http://localhost:15021/Service1.svc";

var dsLoadAllEmployees = function (scope)
{
     //  Load all survey records, from our web server
     $scope.LoadingMessage = "Loading Employees data...";

     var URL = myApp.webServicesURL + "/loadAllEmployees";
     return httpGetFactory(scope, URL);
}

这是我在每个页面上使用的“请稍候”控件。

<please-wait message="{{LoadingMessage}}" ></please-wait>

...它的代码看起来像这样...

myApp.directive('pleaseWait',  
    function ($parse) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                message: '@message'
            },
            link: function (scope, element, attrs) {
                scope.$on('app-start-loading', function () {
                    element.fadeIn(); 
                });
                scope.$on('app-finish-loading', function(){
                    element.animate({
                        top: "+=15px",
                        opacity: "0"
                    }, 500);
                });
            },
            template: '<div class="cssPleaseWait"><span>{{ message }}</span></div>'
        }
    });

使用这种结构,我的任何 Angular 控制器都可以在几行内从 Web 服务加载数据,并在出厂时处理显示/隐藏“请稍候”消息并显示发生的任何错误:

   $scope.LoadAllSurveys = function () {
        DataService.dsLoadAllSurveys($scope).then(function (response) {
            //  Success
            $scope.listOfSurveys = response.GetAllSurveysResult;
        });
   }

不错,嘿?

于 2016-09-01T19:49:42.800 回答
0

我不知道是否是正确的方法,但我把我的模板

 <img id="spinner" ng-src="images/spinner.gif" ng-if="!data" >
 <div ng-repeat="repo in repos | orderBy: repoSortOrder">...</div>
于 2015-04-24T13:50:21.930 回答