angularjs - 每次页面加载时的 ngProgress 加载栏

标签 angularjs

我正在使用 AngularJS 和 ngProgress在我的网站顶部显示类似 YouTube 的加载栏。

酒吧开始,然后通过ajax加载新数据,一旦请求完成,酒吧就完成了。

例子:

var TestCtrl = function( $scope, $location, Tests, ngProgress ) 
{
    // start progressbar
    ngProgress.start();

    $scope.tests = Tests.query(
        function()
        {
            // end progressbar
            ngProgress.complete()
        }
    );
};  

现在我的问题是:如何将这个原则整合到事物的顺序中,这样我就不必为每个 Controller 重复代码?

最佳答案

您可以使用控制 ngProgress 的服务(就像它的包装器一样)并监听 url 中的变化。

  • 每次 url 改变时,事件 $locationChangeSuccess 被广播(更多信息在 $location )我们可以监听调用 ngProgress.start()
  • 但是我们不知道它什么时候完成(我们不能永远在顶部加载栏),因此我们需要在我们的 Controller 中显式调用 ngProgress.complete() 或者我们可以假设我们的异步函数可能需要 5 秒才能完成,并在我们的包装服务中使用计时器调用 ngProgress.complete()
  • 当加载栏已经可见并且 url 发生变化时,我们需要通过调用 ngProgress.reset()
  • 重置栏的状态

您可以使用以下方法来解决这些问题:

angular.module('myApp').factory('Progress', function (ngProgress) {
    var timer;
    return {
        start: function () {
            var me = this;
            // reset the status of the progress bar
            me.reset();
            // if the `complete` method is not called
            // complete the progress of the bar after 5 seconds
            timer = setTimeout(function () {
                me.complete();
            }, 5000);
        },
        complete: function () {
            ngProgress.complete();
            if (timer) {
                // remove the 5 second timer
                clearTimeout(timer);
                timer = null;
            }
        },
        reset: function () {             
            if (timer) {
                // remove the 5 second timer
                clearTimeout(timer);
                // reset the progress bar
                ngProgress.reset();
            }
            // start the progress bar
            ngProgress.start();
        }
    };
});

要监听 url 的变化并显示我们可以使用的进度条:

angular.module('myApp')
    .run(function (Progress) {
        $rootScope.$on('$locationChangeSuccess', function () {
            Progress.start();
        });
    }

现在我们可以通过注入(inject) Progress 服务并在所有异步函数完成时调用方法 Progress.complete() 来手动控制状态栏的完整性(我们也可以通过任何进行异步调用的服务来控制它):

angular.module('myApp')
    .controller('SomeCtrl', function (Progress) {
        setTimeout(function () {
            Progress.complete();
        }, 2000);
    });

关于angularjs - 每次页面加载时的 ngProgress 加载栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18877332/

相关文章:

php - 仅当存在 JSON 数据时才创建页面元素

javascript - Angular JS ng-model 传递给函数 undefined object

javascript - 如何比较两个数组有多少相同的元素?

javascript - Angularjs 中使用 Bindonce 自定义指令值

javascript - Angular 监控 DOM 更改超出 Angular 范围

angularjs - 当我尝试使用时,angularJS 中超出了最大调用堆栈大小 |过滤器 :searchText

angularjs - 按周分页 - AngularJS

javascript - 有没有办法获取 Angular $cacheFactory 中的所有键?

javascript - Controller AngularJs 中的服务注入(inject)

javascript - 登录后angularjs重定向