使用Angularjs,我需要显示一个加载屏幕(一个简单的微调器),直到ajax请求完成为止。请提出带有代码段的任何想法。
$httpProvider.interceptors
它,因为它可以处理ajax请求何时开始和何时结束。这就是为什么$watch
不再需要检测Ajax调用何时开始和结束的原因。
使用Angularjs,我需要显示一个加载屏幕(一个简单的微调器),直到ajax请求完成为止。请提出带有代码段的任何想法。
$httpProvider.interceptors
它,因为它可以处理ajax请求何时开始和何时结束。这就是为什么$watch
不再需要检测Ajax调用何时开始和结束的原因。
Answers:
与其设置范围变量以指示数据加载状态,不如让指令为您完成所有操作:
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();
}
});
}
};
}]);
使用此伪指令,您需要做的就是为任何加载动画元素提供“加载”属性:
<div class="loading-spiner-holder" data-loading ><div class="loading-spiner"><img src="..." /></div></div>
您可以在页面上有多个加载微调器。这些微调框的位置和布局由您决定,指令会自动为您自动打开/关闭。
这是一个例子。它与布尔一起使用简单的ng-show方法。
的HTML
<div ng-show="loading" class="loading"><img src="...">LOADING...</div>
<div ng-repeat="car in cars">
<li>{{car.name}}</li>
</div>
<button ng-click="clickMe()" class="btn btn-primary">CLICK ME</button>
安格拉斯
$scope.clickMe = function() {
$scope.loading = true;
$http.get('test.json')
.success(function(data) {
$scope.cars = data[0].cars;
$scope.loading = false;
});
}
当然,您可以将加载框的html代码移到指令中,然后在$ scope.loading上使用$ watch。在这种情况下:
HTML:
<loading></loading>
ANGULARJS指令:
.directive('loading', function () {
return {
restrict: 'E',
replace:true,
template: '<div class="loading"><img src="..."/>LOADING...</div>',
link: function (scope, element, attr) {
scope.$watch('loading', function (val) {
if (val)
$(element).show();
else
$(element).hide();
});
}
}
})
PLUNK:http://plnkr.co/edit/AI1z21?p = preview
ui-router
,不知道为什么
loading=true
而无法设置
我为此使用ngProgress。
在HTML中包含脚本/ css文件后,将“ ngProgress”添加到依赖项中。完成此操作后,您可以设置类似这样的内容,该功能将在检测到路线更改时触发。
angular.module('app').run(function($rootScope, ngProgress) {
$rootScope.$on('$routeChangeStart', function(ev,data) {
ngProgress.start();
});
$rootScope.$on('$routeChangeSuccess', function(ev,data) {
ngProgress.complete();
});
});
对于AJAX请求,您可以执行以下操作:
$scope.getLatest = function () {
ngProgress.start();
$http.get('/latest-goodies')
.success(function(data,status) {
$scope.latest = data;
ngProgress.complete();
})
.error(function(data,status) {
ngProgress.complete();
});
};
只需记住在执行之前将'ngProgress'添加到控制器依赖项即可。而且,如果您要执行多个AJAX请求,请在主应用程序范围内使用一个增量变量来跟踪AJAX请求何时完成,然后再调用“ ngProgress.complete();”。
使用未决请求是不正确的,因为如Angular文档中所述,此属性主要用于调试目的。
我建议使用拦截器来知道是否有任何活动的异步调用。
module.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($q, $rootScope) {
if ($rootScope.activeCalls == undefined) {
$rootScope.activeCalls = 0;
}
return {
request: function (config) {
$rootScope.activeCalls += 1;
return config;
},
requestError: function (rejection) {
$rootScope.activeCalls -= 1;
return rejection;
},
response: function (response) {
$rootScope.activeCalls -= 1;
return response;
},
responseError: function (rejection) {
$rootScope.activeCalls -= 1;
return rejection;
}
};
});
}]);
然后通过$ watch在指令中检查activeCalls是否为零。
module.directive('loadingSpinner', function ($http) {
return {
restrict: 'A',
replace: true,
template: '<div class="loader unixloader" data-initialize="loader" data-delay="500"></div>',
link: function (scope, element, attrs) {
scope.$watch('activeCalls', function (newVal, oldVal) {
if (newVal == 0) {
$(element).hide();
}
else {
$(element).show();
}
});
}
};
});
参考这个答案
https://stackoverflow.com/a/17144634/4146239
对我来说,这是最好的解决方案,但是有一种避免使用jQuery的方法。
.directive('loading', function () {
return {
restrict: 'E',
replace:true,
template: '<div class="loading"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" width="20" height="20" />LOADING...</div>',
link: function (scope, element, attr) {
scope.$watch('loading', function (val) {
if (val)
scope.loadingStatus = 'true';
else
scope.loadingStatus = 'false';
});
}
}
})
.controller('myController', function($scope, $http) {
$scope.cars = [];
$scope.clickMe = function() {
scope.loadingStatus = 'true'
$http.get('test.json')
.success(function(data) {
$scope.cars = data[0].cars;
$scope.loadingStatus = 'false';
});
}
});
<body ng-app="myApp" ng-controller="myController" ng-init="loadingStatus='true'">
<loading ng-show="loadingStatus" ></loading>
<div ng-repeat="car in cars">
<li>{{car.name}}</li>
</div>
<button ng-click="clickMe()" class="btn btn-primary">CLICK ME</button>
</body>
您需要替换$(element).show();。和(element).show(); $ scope.loadingStatus ='true'; 和$ scope.loadingStatus ='false';
然后,您需要使用此变量来设置元素的ng-show属性。
打字稿和角度实现
指示
((): void=> {
"use strict";
angular.module("app").directive("busyindicator", busyIndicator);
function busyIndicator($http:ng.IHttpService): ng.IDirective {
var directive = <ng.IDirective>{
restrict: "A",
link(scope: Scope.IBusyIndicatorScope) {
scope.anyRequestInProgress = () => ($http.pendingRequests.length > 0);
scope.$watch(scope.anyRequestInProgress, x => {
if (x) {
scope.canShow = true;
} else {
scope.canShow = false;
}
});
}
};
return directive;
}
})();
范围
module App.Scope {
export interface IBusyIndicatorScope extends angular.IScope {
anyRequestInProgress: any;
canShow: boolean;
}
}
模板
<div id="activityspinner" ng-show="canShow" class="show" data-busyindicator>
</div>
CSS
#activityspinner
{
display : none;
}
#activityspinner.show {
display : block;
position : fixed;
z-index: 100;
background-image : url('data:image/gif;base64,R0lGODlhNgA3APMAAPz8/GZmZqysrHV1dW1tbeXl5ZeXl+fn59nZ2ZCQkLa2tgAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAANgA3AAAEzBDISau9OOvNu/9gKI5kaZ4lkhBEgqCnws6EApMITb93uOqsRC8EpA1Bxdnx8wMKl51ckXcsGF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U1RWV1hhTIWJiouMjVcFBjUGBY4WBWw1A5RDT3sTkVQGnGYYaUOYPaVip3MXoDyiP3k3GAeoAwdRnRoHoAa5lcHCw8TFxscduyjKIrOeRKRAbSe3I9Um1yHOJ9sjzCbfyInhwt3E2cPo5dHF5OLvJREAOwAAAAAAAAAAAA==')
-ms-opacity : 0.4;
opacity : 0.4;
background-repeat : no-repeat;
background-position : center;
left : 0;
bottom : 0;
right : 0;
top : 0;
}
如果您使用的是Restangular(非常棒),则可以在api调用期间创建动画。这是我的解决方案。添加响应拦截器和请求拦截器,以发出rootscope广播。然后创建一个指令以侦听该响应和请求。
angular.module('mean.system')
.factory('myRestangular',['Restangular','$rootScope', function(Restangular,$rootScope) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://localhost:3000/api');
RestangularConfigurer.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// .. to look for getList operations
if (operation === 'getList') {
// .. and handle the data and meta data
extractedData = data.data;
extractedData.meta = data.meta;
} else {
extractedData = data.data;
}
$rootScope.$broadcast('apiResponse');
return extractedData;
});
RestangularConfigurer.setRequestInterceptor(function (elem, operation) {
if (operation === 'remove') {
return null;
}
return (elem && angular.isObject(elem.data)) ? elem : {data: elem};
});
RestangularConfigurer.setRestangularFields({
id: '_id'
});
RestangularConfigurer.addRequestInterceptor(function(element, operation, what, url) {
$rootScope.$broadcast('apiRequest');
return element;
});
});
}]);
这是指令:
angular.module('mean.system')
.directive('smartLoadingIndicator', function($rootScope) {
return {
restrict: 'AE',
template: '<div ng-show="isAPICalling"><p><i class="fa fa-gear fa-4x fa-spin"></i> Loading</p></div>',
replace: true,
link: function(scope, elem, attrs) {
scope.isAPICalling = false;
$rootScope.$on('apiRequest', function() {
scope.isAPICalling = true;
});
$rootScope.$on('apiResponse', function() {
scope.isAPICalling = false;
});
}
};
})
;
将此包含在“ app.config”中:
$httpProvider.interceptors.push('myHttpInterceptor');
并添加以下代码:
app.factory('myHttpInterceptor', function ($q, $window,$rootScope) {
$rootScope.ActiveAjaxConectionsWithouthNotifications = 0;
var checker = function(parameters,status){
//YOU CAN USE parameters.url TO IGNORE SOME URL
if(status == "request"){
$rootScope.ActiveAjaxConectionsWithouthNotifications+=1;
$('#loading_view').show();
}
if(status == "response"){
$rootScope.ActiveAjaxConectionsWithouthNotifications-=1;
}
if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){
$rootScope.ActiveAjaxConectionsWithouthNotifications=0;
$('#loading_view').hide();
}
};
return {
'request': function(config) {
checker(config,"request");
return config;
},
'requestError': function(rejection) {
checker(rejection.config,"request");
return $q.reject(rejection);
},
'response': function(response) {
checker(response.config,"response");
return response;
},
'responseError': function(rejection) {
checker(rejection.config,"response");
return $q.reject(rejection);
}
};
});
在此简单的拦截器示例中,我在ajax启动时将鼠标设置为等待状态,而在ajax结束时将其设置为自动状态。
$httpProvider.interceptors.push(function($document) {
return {
'request': function(config) {
// here ajax start
// here we can for example add some class or show somethin
$document.find("body").css("cursor","wait");
return config;
},
'response': function(response) {
// here ajax ends
//here we should remove classes added on request start
$document.find("body").css("cursor","auto");
return response;
}
};
});
必须在应用程序config中添加代码app.config
。我展示了如何在加载状态下更改鼠标,但是在其中可以显示/隐藏任何加载程序内容,或者添加,删除一些显示加载程序的CSS类。
拦截器将在每个ajax调用上运行,因此无需在每个http调用上创建特殊的布尔变量($ scope.loading = true / false等)。
拦截器使用的是内置 于angular jqLite https://docs.angularjs.org/api/ng/function/angular.element中的内置对象,因此不需要Jquery。
使用show和size属性创建一个指令(也可以添加更多内容)
app.directive('loader',function(){
return {
restrict:'EA',
scope:{
show : '@',
size : '@'
},
template : '<div class="loader-container"><div class="loader" ng-if="show" ng-class="size"></div></div>'
}
})
并在html中用作
<loader show="{{loader1}}" size="sm"></loader>
在show变量中,当任何promise运行时传递true,而在请求完成时传递false。活动演示-JsFiddle中的Angular Loader指令示例演示
我在@DavidLin的答案上做了一些简化,以简化它- 删除指令中对jQuery的任何依赖。在生产应用程序中使用它时,我可以确认它能正常工作
function AjaxLoadingOverlay($http) {
return {
restrict: 'A',
link: function ($scope, $element, $attributes) {
$scope.loadingOverlay = false;
$scope.isLoading = function () {
return $http.pendingRequests.length > 0;
};
$scope.$watch($scope.isLoading, function (isLoading) {
$scope.loadingOverlay = isLoading;
});
}
};
}
我使用ng-show
而不是jQuery调用来隐藏/显示<div>
。
这是<div>
我放在开始<body>
标记下方的内容:
<div ajax-loading-overlay class="loading-overlay" ng-show="loadingOverlay">
<img src="Resources/Images/LoadingAnimation.gif" />
</div>
以下是CSS,它提供了覆盖层,可在进行$ http调用时阻止UI:
.loading-overlay {
position: fixed;
z-index: 999;
height: 2em;
width: 2em;
overflow: show;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.loading-overlay:before {
content: '';
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.3);
}
/* :not(:required) hides these rules from IE9 and below */
.loading-overlay:not(:required) {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
CSS致谢@Steve Seeger's-他的帖子:https://stackoverflow.com/a/35470281/335545
您可以添加一个条件,然后通过rootscope对其进行更改。在您的ajax请求之前,您只需调用$ rootScope。$ emit('stopLoader');。
angular.module('directive.loading', [])
.directive('loading', ['$http', '$rootScope',function ($http, $rootScope)
{
return {
restrict: 'A',
link: function (scope, elm, attrs)
{
scope.isNoLoadingForced = false;
scope.isLoading = function () {
return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
};
$rootScope.$on('stopLoader', function(){
scope.isNoLoadingForced = true;
})
scope.$watch(scope.isLoading, function (v)
{
if(v){
elm.show();
}else{
elm.hide();
}
});
}
};
}]);
绝对不是最佳解决方案,但仍然可以使用。