我有这个代码用于图像 slider 和下一个上一个以及自动更改图像功能
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);
});
在 slider 模板中,我有下一个和上一个函数的箭头链接
<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>
我只想在用户点击下一个或上一个 btn 时添加清除 $timeout 功能,每次用户点击下一个或上一个 btn 时,计时器都会清除并在 5 秒后更改图像。
这是关于 image slider 的完整文档
我为此 please look at this 创建了 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;
};
希望对你有帮助。
关于javascript - 如何清除angularjs中的$timeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31981292/