2013-11-05 120 views
9

當使用AngularJS並使用$location.path('/path')進行重定向時,新頁面需要一段時間才能加載,尤其是在移動設備上。AngularJS加載進度條

有沒有辦法添加進度條進行加載?也許像YouTube一樣?

回答

21

對於YouTube的進度條,您可以查看ngprogress。然後在您的應用程序配置完成後(例如),您可以intercept route's events

而且做這樣的事情:

app.run(function($rootScope, ngProgress) { 
    $rootScope.$on('$routeChangeStart', function() { 
    ngProgress.start(); 
    }); 

    $rootScope.$on('$routeChangeSuccess', function() { 
    ngProgress.complete(); 
    }); 
    // Do the same with $routeChangeError 
}); 
+3

你忘了注入ngProgress: .RUN(函數($ rootScope,ngProgress) –

+0

鈮這個答案不再適用看看@ rsobon在本頁底部的答案用於最新的實施。 – adaam

0

如果它是需要時間來加載例如下一個路線在控制器運行之前進行ajax調用(解析路由上的配置),然後利用$ route服務的$ routeChangeStart,$ routeChangeSuccess和$ routeChangeError事件。

註冊監聽這些事件並管理其$範圍內的布爾變量的頂級控制器(ng-view外部)。

在ng-show中使用此變量覆蓋「loading,please wait」div。

如果下一條路線加載速度快(即其控制器運行速度快),但由控制器請求的數據需要很長時間才能加載,那麼恐怕必須管理控制器中spinners的可見性狀態,並且視圖。

類似:

$scope.data = null; 
$http.get("/whatever").success(function(data) { 
    $scope.data = data; 
}); 

<div ng-show="data !== null">...</div> 
<div ng-show="data === null" class="spinner"></div> 
-1

這裏是我用我的應用程序,一個可行的解決方案。 ngProgress是用於顯示更改網址時的加載條的最佳圖書館。

記得要注入ngProgressFactory而不是ngProgress,而不是Luc的解決方案。

angular.module('appRoutes', []).run(function ($rootScope, ngProgressFactory) { 
    $rootScope.$on("$routeChangeStart", function() { 
     $rootScope.progressbar = ngProgressFactory.createInstance(); 
     $rootScope.progressbar.start(); 

    }); 

    $rootScope.$on("$routeChangeSuccess", function() { 
     $rootScope.progressbar.complete(); 
    }); 
}); 

更新十一月-2015 - 分析與鉻時序這種方法後,我觀察到,這將不會是添加加載條正確的道路。當然,訪客可以看到加載欄,但它不會與實際的頁面加載時間同步。

5

由於@ Luc的anwser ngProgress改了一下,現在你只能注入ngProgressFactory,那就必須用來創建ngProgress實例。也違背了@Ketan帕蒂爾的答案,你應該只實例ngProgress 一次

angular.module('appRoutes', []).run(function ($rootScope, ngProgressFactory) { 

    // first create instance when app starts 
    $rootScope.progressbar = ngProgressFactory.createInstance(); 

    $rootScope.$on("$routeChangeStart", function() { 
     $rootScope.progressbar.start(); 
    }); 

    $rootScope.$on("$routeChangeSuccess", function() { 
     $rootScope.progressbar.complete(); 
    }); 
}); 
+0

非常感謝! – adaam