我有一个微调器,显示为 ng-show="loading>0"
有没有办法可以延迟(比如 1 秒)显示此微调器?
我无法使用超时,因为有多个请求时,加载计数器将不同步。
我需要的是通过 css 转换或类似的方式延迟 ng-show
最佳答案
我怀疑您正在寻找一个包含延迟的通用旋转器。标准,在 200ms
或类似的时间后显示。
这是指令的完美候选,而且实际上很容易完成。
我知道这是一个很长的代码示例,但主要部分是指令。这很简单。
监听一些范围变量并在一些可配置的延迟后显示。如果操作花费的时间超过延迟,它将被取消并且永远不会显示。
(function() {
'use strict';
function SpinnerDirective($timeout) {
return {
restrict: 'E',
template: '<i class="fa fa-cog fa-spin"></i>',
scope: {
show: '=',
delay: '@'
},
link: function(scope, elem, attrs) {
var showTimer;
//This is where all the magic happens!
// Whenever the scope variable updates we simply
// show if it evaluates to 'true' and hide if 'false'
scope.$watch('show', function(newVal){
newVal ? showSpinner() : hideSpinner();
});
function showSpinner() {
//If showing is already in progress just wait
if (showTimer) return;
//Set up a timeout based on our configured delay to show
// the element (our spinner)
showTimer = $timeout(showElement.bind(this, true), getDelay());
}
function hideSpinner() {
//This is important. If the timer is in progress
// we need to cancel it to ensure everything stays
// in sync.
if (showTimer) {
$timeout.cancel(showTimer);
}
showTimer = null;
showElement(false);
}
function showElement(show) {
show ? elem.css({display:''}) : elem.css({display:'none'});
}
function getDelay() {
var delay = parseInt(scope.delay);
return angular.isNumber(delay) ? delay : 200;
}
}
};
}
function FakeService($timeout) {
var svc = this,
numCalls = 0;
svc.fakeCall = function(delay) {
numCalls += 1;
return $timeout(function() {
return {
callNumber: numCalls
};
}, delay || 50);
};
}
function MainCtrl(fakeService) {
var vm = this;
vm.makeCall = function(delay) {
vm.isBusy = true;
fakeService.fakeCall(delay)
.then(function(result) {
vm.result = result;
}).finally(function() {
vm.isBusy = false;
});
}
}
angular.module('spinner', [])
.service('fakeService', FakeService)
.controller('mainCtrl', MainCtrl)
.directive('spinner', SpinnerDirective);
}());
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<div class="container" ng-app="spinner">
<div class="row" ng-controller="mainCtrl as ctrl">
<div class="col-sm-12">
<h2>{{ctrl.result | json}}
<spinner show="ctrl.isBusy" delay="200"></spinner>
</h2>
<button type="button"
class="btn btn-primary"
ng-click="ctrl.makeCall(2000)"
ng-disabled="ctrl.isBusy">Slow Call
</button>
<button type="button"
class="btn btn-default"
ng-click="ctrl.makeCall()"
ng-disabled="ctrl.isBusy">Fast Call
</button>
</div>
</div>
</div>
关于angularjs - ng-show指令可以延迟使用吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27842299/