gpt4 book ai didi

angularjs - 为什么在 ng-show 指令评估为 false 后不添加 ng-hide 类?

转载 作者:行者123 更新时间:2023-12-02 01:54:25 27 4
gpt4 key购买 nike

即使 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;
}

我正在使用 angular 1.2.3 和 angular-animate 1.2.3

最佳答案

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() 将手动检查更改。

关于angularjs - 为什么在 ng-show 指令评估为 false 后不添加 ng-hide 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21010156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com