查看视图在angularjs中更改时的视图
看看this thread它看起来像$httpProvider.responseInterceptors
是一个很好的地方添加这种类型的东西。
This fiddle显示了一个很好的示例,说明在哪里添加代码以启动/停止ajax请求的微调器。 This fiddle是类似的,但实际上显示并隐藏了“加载...”div。
如果你只是想显示微调时的看法改变,你可以限制你的开始/停止代码时content-type
等于text/html
类似于显示了application/json
this post来。
注意:在我的测试中,当检索我的.html文件时,spinnerFunction
中的headersGetter()['Content-Type']
被忽略,而在进行服务调用时它被填充。
我认为一个更简单,适应性更强的方法是使用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");
}
});
请注意,$。主动是未公开。
谢谢你!〜 – matsko 2012-11-05 23:11:33
任何时候:)我只是在我的头上打了几个小时,然后想到我会分享。 – Stone 2012-11-05 23:47:24
顺便说一句,你也可以使用'$ scope。$ watch'来达到同样的效果,而不使用'setTimeout'。这将是一个更好的选择,因为这符合$范围摘要。你也可以使用这个插件,但是当你完成的时候你必须手动调用'$ scope.onReady()'。 https://github.com/yearofmoo/AngularJS-Scope.onReady – matsko 2012-11-05 23:50:57
完美。正是我需要的。谢谢:) – matsko 2012-08-03 16:25:20
这只适用于你有一个单一的Ajax请求。 – Meeker 2013-10-22 04:07:41
目前是1.2吗? – ericpeters0n 2014-03-09 04:52:28