即使ng-show评估为false,我们的加载图标(微调器)有时仍然可见。
这是指令:
angular.module("app.directives").directive("loadingIcon", function() {
return {
restrict: "A",
replace: true,
link: function (scope, element) {
scope.showLoader = false;
scope.$on('event:httpRequestStarted', function () {
// got the request start notification, show the element
scope.showLoader = true;
});
scope.$on('event:httpRequestsCompleted', function () {
// got the request completed notification, hide the element
scope.showLoader = false;
});
},
template: "<div ng-show='showLoader' class='fade-in-out loading-icon spin-fx ng-hide' ng-cloak></div>"
}
});
这里是httpInterceptor,如果微调器应该打开,它会广播:
// interceptor to show loading icon
$httpProvider.interceptors.push(['$q','$rootScope', function($q, $rootScope) {
window.requestCount = 0;
return {
request: function(config) {
window.requestCount += 1;
console.log('start request', config, window.requestCount)
$rootScope.$broadcast('event:httpRequestStarted');
return config || $q.when(config);
},
response: function(response) {
$rootScope.$broadcast('event:httpRequestSuccess', response);
window.requestCount -= 1;
console.log('got response', response, window.requestCount)
if ((window.requestCount) === 0) {
console.log('stop spinny')
$rootScope.$broadcast('event:httpRequestsCompleted');
}
return response || $q.when(response);
},
从console.log输出和window.requestCount,逻辑是正确的。在大多数情况下,这是有效的。但有时(可能存在竞争条件?),加载图标仍然存在于类ng-hide-add ng-animate-active ng-hide-add-active
但是没有ng-hide
。我认为如果ng-show是假的,它应该添加一个ng-hide
类?
任何人都可以了解竞争条件可能是什么?
编辑:
是的,ngAnimate模块包含在我们的应用中。这是用于加载图标的CSS:
.loading-icon {
background-image: url("/images/loading-icon.png");
background-repeat: no-repeat;
background-position: 0 0;
width: 40px;
height: 40px;
z-index: 100000;
position: fixed;
right: 50%;
top: 50%;
margin: -20px 0 0 -20px;
}
.spin-fx {
-moz-animation: spin-fx 2s infinite linear;
-o-animation: spin-fx 2s infinite linear;
-webkit-animation: spin-fx 2s infinite linear;
animation: spin-fx 2s infinite linear;
}
// loading icon
.fade-in-out {
transition:linear 1s;
}
.fade-in-out.ng-enter {
opacity:0;
}
.fade-in-out.ng-enter-active {
opacity:1;
}
.fade-in-out.ng-leave {
opacity:1;
}
.fade-in-out.ng-leave-active {
opacity:0;
}
我使用角度1.2.3和角度动画1.2.3
答案 0 :(得分:2)
scope.$on('event:httpRequestStarted', function () {
scope.showLoader = true;
scope.$apply(); // Apply changes
});
scope.$on('event:httpRequestsCompleted', function () {
scope.showLoader = false;
scope.$apply(); // Apply changes
});
AngularJS在使用事件时不会检查更改(例如$on
,$broadcast
,$emit
)。 $scope.apply()
会手动检查更改。
答案 1 :(得分:0)
似乎可能在角度或角度动画本身中存在问题。 https://github.com/angular/angular.js/blob/master/CHANGELOG.md
我从1.2.3升级到1.2.7,之前一直可重现的问题现在已经消失。检查时,$('。loading-icon')显示现在正确应用了ng-hide类。