AngularJS用于ng-repeat的简单预加载器?

时间:2015-10-05 20:31:13

标签: javascript angularjs

我有一个显示预加载器的div。我想在我的ng-repeat完成所有数据加载后隐藏该div。

到目前为止,这是我可以拼凑的东西,但这些碎片尚未发挥作用。

还有另一种简单的方法吗?

Plunker http://plnkr.co/edit/ilgOZzIy2axSi5Iy85C7?p=preview

HTML:

          
<div ng-controller="locationAccordionCtrl">
    <div ng-repeat="location in locations" on-finish-render="ngRepeatFinished">

      {{location.siteName}}

      <ul>
          <li ng-repeat="listOfLocations in location.locationsList track by $index">
              {{listOfLocations}}
          </li>
      </ul>

    </div>
</div>

控制器:

App.controller('locationAccordionCtrl', function ($scope) {

  $scope.locations = [
    {
      "siteName":"First Location",
      "locationsList":['First Location 1', 'First Location 2', 'First Location 3']
    },
    {
      "siteName":"Second Location",
      "locationsList":['Second Location 1', 'Second Location 2', 'Second Location 3']
    },
    {
      "siteName":"Third Location",
      "locationsList":['Third Location 1', 'Third Location 2', 'Third Location 3']
    }
  ];

// Hide preloader after repeater is finished loading data
App.directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    }
});

// hide preloader
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
    $scope.hidePreLoader = true;
});

});

1 个答案:

答案 0 :(得分:1)

这是你如何做到这一点

    var App = angular.module('App.directives', []);
     App.directive('routeLoadingIndicator', function($rootScope){
       return {
       restrict:'E',
       template:"<h1 ng-if='isRouteLoading'
       style='
       position: fixed;
       width: 100%;
       height: 100%;
       background: rgb(255, 255, 255) none repeat scroll 0% 0%;
       margin: 0px; padding: 0px; left: 0px;
       top: 0px; right: 0px; bottom: 0px;
       z-index: 2147483647;
       ' >Loading...</h1>",
       link:function(scope, elem, attrs){
         scope.isRouteLoading = false;

         $rootScope.$on('$routeChangeStart', function(){
           scope.isRouteLoading = true;
         });

         $rootScope.$on('$routeChangeSuccess', function(){
           scope.isRouteLoading = false;
         });
       }
     };
    });