[英]AngularJs - set $timeout delay dynamically in a directive
I have this next method declared in a directive to show slides with a delay : 我在指令中声明了下一个方法,以延迟显示幻灯片:
var timer;
var sliderFunc = function(){
timer = $timeout(function(){
scope.next();
timer = $timeout(sliderFunc, 5000);
}, 5000);
};
sliderFunc();
With this example, everything is good. 在这个例子中,一切都很好。
But i want to set a different delay between first (1000) and others slides (5000). 但是我想在第一张幻灯片(1000张)和其他幻灯片(5000张)之间设置不同的延迟。 So i tried to set 'delay' parameter dynamically as this example : 所以我尝试动态设置'delay'参数作为此示例:
var timer;
scope.timeout = 5000;
var sliderFunc = function(){
timer = $timeout(function(){
scope.next();
timer = $timeout(sliderFunc, scope.timeout);
}, scope.timeout);
};
sliderFunc();
In the first occurrence, delay is good, but in the next steps 'scope.timeout' is undefined. 第一次出现时,延迟是好的,但是在接下来的步骤中,“ scope.timeout”是未定义的。
Does any one have an idea how to solve it? 有谁知道如何解决吗?
UPDATE 1 : 更新1:
If i inspect my code in the first occurence, 'delay' (equal to scope.timeout in the last example) is equal to '5000' when i enter in 'slideFunc', but is undefined in second function and on the next steps : 如果我在第一次出现时检查我的代码,则当我输入“ slideFunc”时,“延迟”(等于上一个示例中的scope.timeout)等于“ 5000”,但在第二个函数和后续步骤中未定义:
UPDATE 2 : 更新2:
This is my entire directive : 这是我的整个指令:
'delay' is supposed to be set in my directive declaration. “延迟”应该在我的指令声明中设置。
angular.module('myApp.central.directives', []).
directive('slider', function($timeout) {
return {
restrict: 'AE',
replace: true,
scope: {
list: '=',
delay: '='
},
link: function (scope, elem, attrs) {
scope.currentIndex = 0;
scope.next = function(){
if (scope.currentIndex < scope.list.length -1) {
scope.currentIndex++;
} else {
scope.currentIndex = 0;
}
};
scope.$watch('currentIndex',function(){
// some code useless for this problem
});
/* Start: For Automatic slideshow*/
var timer;
scope.delay = 5000;
var sliderFunc = function(){
timer = $timeout(function(){
scope.next();
timer = $timeout(sliderFunc, scope.delay);
}, scope.delay);
};
sliderFunc();
scope.$on('$destroy',function(){
$timeout.cancel(timer);
});
/* End : For Automatic slideshow*/
},
templateUrl: 'partials/widgets/slider-template.html'
};
});
When using two way bindings you can't just bind a scalar value such as an integer. 使用双向绑定时,您不能仅绑定标量值(例如整数)。 You must bind to a property of an object. 您必须绑定到对象的属性。 This is because of the way it stores a reference to the object. 这是因为它存储了对对象的引用的方式。 Basically anywhere you use a binding make sure there is a dot. 基本上在任何使用绑定的地方,请确保有一个点。
For example 例如
$scope.test = {
v: [],
z: 1000
}
<div ng-app="myApp.central.directives" ng-controller="ctrl">
<slider list="test.v" delay="test.z"></slider>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.