第二个Angular指令首先遭遇$ timeout

时间:2015-04-01 19:25:06

标签: angularjs angularjs-directive timeout

在构建简单的Angular App时,我使用了两个指令。 第一个指令创建幻灯片,第二个指令为一些读取链接提供服务。

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相当新,但我认为指令,不同的范围不会相互干扰。

我能做什么,所以我的阅读链接会立即触发?

2 个答案:

答案 0 :(得分:0)

这是因为在第二个指令中,您正在jQuery单击事件中更新范围,该事件超出了Angular生命周期。

然后将在下一个摘要周期刷新视图,例如由任何$timeout调用触发。

快速而肮脏的解决方法是在第二个指令的点击侦听器中调用scope.$apply()(或scope.$digest())。

更好的解决方法是使用ng-click指令而不是jQuery监听器以角度方式捕获click事件(然后让它们成为生命周期的一部分 - 无需手动$ apply)

更新:以下是使用ng-click

的方法
<a class="readmore" ng-click="more = !more">Read more</a>

<小时/> 作为旁注,您应该使用$interval代替$timeout,因为这是您实际模拟的内容。

答案 1 :(得分:0)

您正在修改范围。更多角度上下文。请调用范围。$ digest()那里

  elem.find('.readmore').bind('click', function() {
            scope.more = scope.more === false ? true : false;
            scope.$digest();
        });