为AngularJS添加Ajax载入动画
因为效率问题,我的小项目使用AngularJS的http服务加载数据时会有明显的卡顿现象,需要一种机制告诉用户后台正在加载数据,让用户耐心等待,而不是以为网页没有响应。想到很多网站中使用的载入动画。
在网上找到一个很棒的例子,直接拿来使用。
《Angularjs loading screen on ajax request》
代码如下
angular.module('directive.loading', [])
.directive('loading', ['$http' ,function ($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();
}
});
}
};使用AngularJS的directive指令来设置载入数据时需要显示的组件,当加载数据时,显示该组件,不加载时,隐藏该组件。通过$http服务的pendingRequests属性来检测是否有数据在加载,用统一的方式显示加载动画,不用为每一次ajax请求单独设置。
我在项目中使用Bootstrap的对话框加进度条构造加载动画
指令也被改为
sms_log_reporter_app.directive('loading', ['$http' ,function ($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){
$('.loading-modal').modal('show');
elm.show();
}else{
$('.loading-modal').modal('hide');
elm.hide();
}
});
}
};
}]);显示效果如下图所示
