在我的agnularjs指令中,我有对象包含某些脚本的逻辑
$scope.slider = {
increment: 0,
step: 1,
positionTop: 0,
init: function (step, isClick) {
if(isClick) clearInterval($scope.interval);
...rest of script...
然后在$scope.slider
关闭之后(}
)我有这段代码
$timeout(function () {
$scope.slider.changeSlide($scope.slider.step);
$scope.interval = setInterval(function () {
$scope.slider.step++;
if($scope.slider.step === 5) $scope.slider.step = 1;
$scope.slider.changeSlide($scope.slider.step);
}, 5000);
});
在页面加载时,我开始init
方法工作,然后当用户另外点击此html标记时
<span class="main__last-added-dot"
data-ng-class="slider.step == 1 ? 'main__last-added-dot--active' : ''"
data-ng-click="slider.init(1, true);"></span>
它清除间隔,这意味着它停止工作,我没有设置新的间隔,因为我不知道如何。我正在使用angularjs $ timeout来启动间隔,因为我正在处理的div被收集在后端调用中,所以我需要等待它们。
我尝试将间隔分配给另一个范围变量并像这样调用它
在$scope.slider
对象中的init方法中
$timeout(function(){ $scope.startInterval() });
低于$scope.slider
对象:
$timeout(function () {
$scope.startInterval = function() {
$scope.interval = setInterval(function () {
console.log('fire function interval');
$scope.slider.step++;
if($scope.slider.step === 5) $scope.slider.step = 1;
$scope.slider.changeSlide($scope.slider.step);
}, 5000);
};
$scope.startInterval();
});
但它创造了某种循环,我真的不知道它的工作非常奇怪。
我做错了如何停止此间隔并再次启动它,在跨度点击后我要将秒数清除为0 ..
我添加demo。
答案 0 :(得分:1)
您可以在下面的代码中执行以下操作,也请查看适用于您的指定方案的 plunker 示例。
<强>指令:强>
app.directive('myElement', ['$interval', '$timeout',
function($interval, $timeout) {
return {
restrict: 'E',
templateUrl: 'template.html',
link: function(scope) {
scope.timer=5000;
scope.step = 1;
function updateTime() {
if(scope.step==4) scope.step=0;
scope.step++;
}
scope.stopTime = $interval(updateTime, scope.timer);
scope.resetTimer=function(step){
scope.step = step;
$interval.cancel(scope.stopTime);
scope.stopTime = $interval(updateTime, scope.timer);
}
}
}
}]);
答案 1 :(得分:0)
您应该命名您的函数并在init
中重置其间隔,如下所示:
$scope.slider = {
increment: 0,
step: 1,
positionTop: 0,
init: function (step, isClick) {
if(isClick) clearInterval($scope.interval);
$scope.interval = setInterval(intervalSlide, 5000); // Reset interval here
...rest of script...
};
// Name your function, no need to attach it to $scope
function intervalSlide() {
$scope.slider.step++;
if($scope.slider.step === 5) $scope.slider.step = 1;
$scope.slider.changeSlide($scope.slider.step);
}
$timeout(function () {
$scope.slider.changeSlide($scope.slider.step);
$scope.interval = setInterval(intervalSlide, 5000);
});