2012-08-02 32 views

回答

12

看看this thread它看起來像$httpProvider.responseInterceptors是一個很好的地方添加這種類型的東西。

This fiddle顯示了一個很好的示例,說明在哪裏添加代碼以啓動/停止a​​jax請求的微調器。 This fiddle是類似的,但實際上顯示並隱藏了「加載...」div。

如果你只是想顯示微調時的看法改變,你可以限制你的開始/停止代碼時content-type等於text/html類似於顯示了application/jsonthis post來。

注意:在我的測試中,當檢索我的.html文件時,spinnerFunction中的headersGetter()['Content-Type']被忽略,而在進行服務調用時它被填充。

+0

完美。正是我需要的。謝謝:) – matsko 2012-08-03 16:25:20

+0

這隻適用於你有一個單一的Ajax請求。 – Meeker 2013-10-22 04:07:41

+0

目前是1.2嗎? – ericpeters0n 2014-03-09 04:52:28

9

我認爲一個更簡單,適應性更強的方法是使用AngularJS $http.pendingRequests.length調用。它返回掛起的ajax呼叫計數。所以當它達到0時,你的頁面已經完成加載。

您可以創建一個指令,在任何元素上插入加載div(scrim),然後等待所有ajax調用來解析並刪除您的微調器。

下面的代碼的肉,讓您的AngularJS指令:

 // Prepend the loading div to the dom element that this directive is applied. 
     var scrim = $('<div id="loading"></div>'); 
     $(scrim).prependTo(domElement); 

     /** 
     * returns the number of active ajax requests (angular + jquery) 
     * $.active returns the count of jQuery specific unresolved ajax calls. It becomes 0 if 
     * there are no calls to be made or when calls become finished. 
     * @return number of active requests. 
     */ 
     function totalActiveAjaxRequests() { 
      return ($http.pendingRequests.length + $.active); 
     } 

     /** 
     * Check for completion of pending Ajax requests. When they're done, 
     * remove the loading screen and show the page data. 
     */ 
     scope.$watch(totalActiveAjaxRequests, function whenActiveAjaxRequestsChange() { 
      if(totalActiveAjaxRequests() === 0){ 
       $log.log("done loading ajax requests"); 
       $(scrim).remove(); 
       $(domElement).css("position", "inherit"); 
      } 
     }); 

請注意,$。主動是未公開。

+0

謝謝你!〜 – matsko 2012-11-05 23:11:33

+0

任何時候:)我只是在我的頭上打了幾個小時,然後想到我會分享。 – Stone 2012-11-05 23:47:24

+0

順便說一句,你也可以使用'$ scope。$ watch'來達到同樣的效果,而不使用'setTimeout'。這將是一個更好的選擇,因爲這符合$範圍摘要。你也可以使用這個插件,但是當你完成的時候你必須手動調用'$ scope.onReady()'。 https://github.com/yearofmoo/AngularJS-Scope.onReady – matsko 2012-11-05 23:50:57