简体   繁体   中英

How to implement loading directive AngularJS

I am trying to implement loading sniper... But problem is when I put sniper inside html it not working. here is my direcitve:

angular.module('commentsApp', [])
        .directive('loading', loading);


function loading($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();
                }
            });
        }
    };
}

Here is my html:

<div class="loading-spiner-holder" data-loading ><div class="loading-spiner"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" /></div></div>

In my commentsController I added like this:

angular.module('commentsApp')
        .controller('CommentsCtrl',function(loading){

Anyone know what is problem?

Check working demo: JSFiddle . Your problem is maybe just because angular.element does not have functions show and hide .

scope.isLoading = function () {
    scope.remained = $http.pendingRequests.length;
    return $http.pendingRequests.length > 0;
};
scope.iAmLoading = scope.isLoading();

scope.$watch(scope.isLoading, function (v) {
    scope.iAmLoading = v;
    if (!v) console.log('All loaded');
});

And HTML:

<div ng-show="iAmLoading" loading>Loading ({{ remained }} remainded) ...</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM