如何在数秒后显示AngularJS中的加载图标?

时间:2017-02-03 08:56:04

标签: javascript angularjs loading

如果任何HTTP请求花费的时间超过2秒,我想显示一个加载图标。我正在使用以下代码在发出HTTP请求时立即显示加载图标:

<div data-loading id="divLoading">
    <img src="http://loadinggif.com/images/image-selection/3.gif" />
</div>

<script>
app.directive('loading', ['$http', function ($http) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            scope.isLoading = function () {
                return $http.pendingRequests.length > 0;
            };

            scope.$watch(scope.isLoading, function (v) {
                if (v) {
                    elm.show();
                } else {
                    elm.hide();
                }
            });
        }
    }
}]);
</script>

注意:我是AngularJS的新手。

我该如何做到这一点?

2 个答案:

答案 0 :(得分:0)

  

您可以使用this spinner指令。   您也可以安装为节点模块:

 npm install angular-spinners

<强>用法

<spinner name="testSpinner"
img-src="http://loadinggif.com/images/image-selection/3.gif"></spinner>

<强>脚本

**This script won't work here.So i have added a working plunk.**

&#13;
&#13;
angular.module("myApp",['angularSpinners'])
.controller('ctr1', function($scope,sample, spinnerService){
   setLoading(true, "testSpinner");
   sample.sampleFn().then(function(data){
     $scope.data=data;
     setLoading(false, "testSpinner");
   })
   
   function setLoading(loading, element) {
      if (loading) {
          spinnerService.show(element);
      } else {
          spinnerService.hide(element);
      }
  }
})
.factory('sample', function($http){
  return {
    sampleFn : sampleFn
  }
  
  function sampleFn(){
    return $http.get('response.json').then(function(response){
      return response.data;
    }, function(){
      $q.reject("Failed");
    })
  }
})
&#13;
&#13;
&#13;

Sample Working Plunk

答案 1 :(得分:0)

步骤1:每当http请求发生时,都会向函数应用延迟 第2步:获取变量并在启动时将其定义为false,并在获得http响应后尝试生效。
步骤3:延迟2秒后评估上面定义的变量,如果它是假则表示在步骤1函数内显示加载。