我有图像滑块和下一个上一个和自动更改图像功能的代码
scope.next = function () {
scope.currentIndex < scope.images.length - 1 ? scope.currentIndex++ : scope.currentIndex = 0;
};
scope.prev = function () {
scope.currentIndex > 0 ? scope.currentIndex-- : scope.currentIndex = scope.images.length - 1;
};
scope.$watch('currentIndex', function () {
scope.images.forEach(function (image) {
image.visible = false;
});
scope.images[scope.currentIndex].visible = true;
});
var timer;
var sliderFunc = function () {
timer = $timeout(function () {
scope.next();
timer = $timeout(sliderFunc, 5000);
}, 5000);
};
sliderFunc();
scope.$on('$destroy', function () {
$timeout.cancel(timer);
});
在滑块模板中,我有下一个和上一个功能的箭头链接
<div class="arrows">
<a href="#" ng-click="prev()">
<img src="tasavir/omgh/left-arrow.png" />
</a>
<a href="#" ng-click="next()">
<img src="tasavir/omgh/right-arrow.png" />
</a>
</div>
我只是想在用户单击下一个或上一个按钮时添加清除 $timeout 功能,并且每次用户单击下一个或上一个按钮时,计时器都会清除并在 5 秒后更改图像。
这是关于 图像滑块
的完整文档我为此创建了 JSFiddle 请看这个
这是我的第三次尝试:https://jsfiddle.net/koljada/8cLw6wch/22/
var timer = $interval(function () {
scope.changeImage();
}, 5000);
scope.next = function () {
$interval.cancel(timer);
timer = $interval(function () {
scope.changeImage();
}, 5000);
};
scope.changeImage = function () {
scope.currentIndex < scope.images.length - 1
? scope.currentIndex++
: (scope.currentIndex = 0);
};
您可以通过检查标志来设置
$scope.next
函数的超时。
标记
<div class="arrows">
<a href="#" ng-click="prev()">
<img src="tasavir/omgh/left-arrow.png" />
</a>
<a href="#" ng-click="next(true)">
<img src="tasavir/omgh/right-arrow.png" />
</a>
</div>
代码
var timer;
var sliderFunc = function () {
timer = $timeout(function () {
scope.next(false);
}, 5000);
};
scope.next = function(setTimeoutToNext){
scope.currentIndex < scope.images.length - 1 ? scope.currentIndex++ : scope.currentIndex = 0;
if(setTimeoutToNext)
$timeout.cancel(timer); //here it will clear the timeout
}