如何实现加载指令AngularJS

时间:2015-09-17 10:42:20

标签: javascript angularjs

我正在尝试加载狙击手...但问题是当我把狙击手放在html里面时它不起作用。这是我的指示:

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

这是我的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>

在我的commentsController中,我添加了这样的内容:

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

任何人都知道什么是问题?

1 个答案:

答案 0 :(得分:2)

检查工作演示:JSFiddle。您的问题可能只是因为angular.element没有函数showhide

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');
});

和HTML:

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