Angularjs 第二个Angular指令在第一个指令中遇到$timeout
在构建一个简单的Angular应用程序时,我使用了两个指令。 第一个指令创建幻灯片,第二个指令提供一些readmore链接Angularjs 第二个Angular指令在第一个指令中遇到$timeout,angularjs,angularjs-directive,timeout,Angularjs,Angularjs Directive,Timeout,在构建一个简单的Angular应用程序时,我使用了两个指令。 第一个指令创建幻灯片,第二个指令提供一些readmore链接 app.directive('slider', function($timeout) { return { restrict: 'AE', replace: true, scope: { images: '=' }, link: function(scope, e
app.directive('slider', function($timeout) {
return {
restrict: 'AE',
replace: true,
scope: {
images: '='
},
link: function(scope, elem, attrs) {
var timer;
scope.currentIndex = 0; // Initially the index is at the first image
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;
};
var sliderFunc = function() {
timer = $timeout(function() {
scope.next();
timer = $timeout(sliderFunc, 5000);
}, 10);
};
sliderFunc();
scope.$watch('currentIndex', function() {
scope.images.forEach(function(image) {
image.visible = false; // make every image invisible
});
if (scope.images.length > 0) {
scope.images[scope.currentIndex].visible = true; // make the current image visible
}
});
scope.$on('$destroy', function() {
$timeout.cancel(timer); // when the scope is getting destroyed, cancel the timer
});
},
templateUrl: 'app/slider.tpl.html'
};
})
.directive('readMore', function() {
return {
restrict: 'A',
scope: true,
link: function(scope, elem, attrs) {
scope.more = false;
elem.find('.readmore').bind('click', function() {
scope.more = scope.more === false ? true : false;
});
}
};
});
这两个指令都按预期工作
第一个指令使用$timeout,因此幻灯片图像每5秒循环一次
readmore链接中存在问题。
单击链接时,脚本指令最多等待5秒。要执行,幻灯片同时也会执行
我对Angular还比较陌生,但我认为不同范围的指令不会相互干扰
我该怎么做才能立即触发我的readmore链接呢?这是因为在第二条指令中,您正在jQuery单击事件中更新范围,这超出了生命周期 然后在下一个摘要周期刷新视图,例如,任何$timeout调用都会触发该周期 一个快速而肮脏的修复方法是在第二个指令上的click侦听器中调用scope.$apply或scope.$digest 更好的修复方法是使用ng click指令而不是jQuery侦听器以角度方式捕获单击事件,然后将其作为其生命周期的一部分—无需手动应用$apply 更新:以下是如何使用ng单击:
作为旁注,您可能应该使用$interval而不是$timeout,因为它是您实际模拟的对象。您正在修改作用域。更多内容超出角度上下文。请在此处调用作用域。$digest
elem.find('.readmore').bind('click', function() {
scope.more = scope.more === false ? true : false;
scope.$digest();
});
感谢$interval提示,这感觉好多了。我尝试使用ng click代替jQuery监听器,但我仍然缺乏使其工作的技能。html锚点与调用指令的元素不同。ng click在那里似乎不起作用。Title
Lorum ipsum。
Lorum ipsum long…
阅读更多您需要将表达式传递给ng click,如ng click=readmore请注意括号。然后在$scope.readmore中,您可以放置一个函数来完成此任务。或者,如果没有函数,您可以直接放置所有逻辑:ng click=more=!更多!将切换布尔值,true为false,false为true。我已经用这个例子更新了我的答案。这样做会更干净,请继续尝试直到成功,我们可以帮助你。很高兴成功。要记住的主要思想是,使用jQuery从来都不是一个好主意,这就是为什么默认情况下它不包含在Angular中:始终尝试以Angular的方式做事,这样可以避免许多问题。 elem.find('.readmore').bind('click', function() {
scope.more = scope.more === false ? true : false;
scope.$digest();
});