我正在使用AngularJS的$http服务来进行Ajax请求。

如何在Ajax请求执行时显示旋转GIF(或另一种类型的忙碌指示器)?

我在AngularJS文档中没有看到类似ajaxstartevent的东西。


当前回答

加上@Adam的回答,

按照建议使用ng-show,但是,在您的情况下,您希望该功能具有多个请求,并在加载器被隐藏之前等待所有请求。

<span ng-show="pendingRequests > 0">
    <img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" style="height:20px;"/>
</span>

然后在控制器中:

$scope.pendingRequests++;

let url = '/whatever_Your_URL_Is'
$http.get(url)
  .then(function(response) {
      $scope.pendingRequests--;
})

其他回答

显示不同url更改之间加载的另一个解决方案是:

$rootScope.$on('$locationChangeStart', function() {
  $scope.loading++;
});

$rootScope.$on('$locationChangeSuccess', function() {
  $timeout(function() {
    $scope.loading--;
  }, 300);
});

然后在标记中用ng-show="loading"切换旋转器。

如果你想在ajax请求中显示它,只需添加$scope。当请求开始和结束时加载++,添加$scope.loading——。

如果你正在使用ngResource,对象的$resolved属性对加载器很有用:

对于资源,如下所示:

var User = $resource('/user/:id', {id:'@id'});
var user = User.get({id: 1})

你可以将加载器链接到资源对象的$resolved属性:

<div ng-hide="user.$resolved">Loading ...</div>

简单的方法没有拦截器或jQuery

这是一种显示旋转器的简单方法,不需要第三方库、拦截器或jQuery。

在控制器中设置和重置标志位。

function starting() {
    //ADD SPINNER
    vm.starting = true;
    $http.get(url)
      .then(function onSuccess(response) {
        vm.data = response.data;
    }).catch(function onReject(errorResponse) {
        console.log(errorResponse.status);
    }).finally(function() {
        //REMOVE SPINNER
        vm.starting = false;
    });
};

在HTML中,使用标记:

<div ng-show="vm.starting">
    <img ng-src="spinnerURL" />
</div>

<div ng-hide="vm.starting">
    <p>{{vm.data}}</p>
</div>

vm。当XHR开始时设置为true,当XHR完成时清除。

https://github.com/wongatech/angular-http-loader是一个很好的项目。

例如http://wongatech.github.io/angular-http-loader/

下面的代码显示了发生请求时的模板示例/loader.tpl.html。

<div ng-http-loader template="example/loader.tpl.html"></div>

如果我们知道DRY的概念,那么所有的答案都是复杂的,或者需要在每个请求上设置一些变量,这是非常错误的做法。这里是一个简单的拦截器的例子,当ajax启动时,我将鼠标设置为等待,当ajax结束时设置为自动。

$httpProvider.interceptors.push(function($document) {
    return {
     'request': function(config) {
         // here ajax start
         // here we can for example add some class or show somethin
         $document.find("body").css("cursor","wait");

         return config;
      },

      'response': function(response) {
         // here ajax ends
         //here we should remove classes added on request start

         $document.find("body").css("cursor","auto");

         return response;
      }
    };
  });

代码必须添加到应用程序配置app.config中。我展示了如何改变鼠标加载状态,但在那里,它是可以显示/隐藏任何加载器内容,或添加,删除一些css类显示加载器。

拦截器将在每次ajax调用上运行,因此不需要创建特殊的布尔变量($scope. js)。加载=true/false等)在每个HTTP调用。