【发布时间】:2015-04-01 19:25:06
【问题描述】:
在构建一个简单的 Angular 应用程序时,我使用了两个指令。 第一个指令创建幻灯片,第二个指令提供一些阅读链接。
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 秒循环一次。
阅读更多链接中存在问题。 当我单击链接时,脚本(指令)等待(最多)5 秒。执行,同时幻灯片也执行。
我对 Angular 还很陌生,但我认为具有不同作用域的指令不会相互干扰。
我该怎么做才能让我的阅读链接立即触发?
【问题讨论】:
标签: angularjs angularjs-directive timeout