AngularJs - 在指令中动态设置$ timeout延迟

时间:2014-12-03 10:17:53

标签: javascript angularjs timeout

我在指令中声明了下一个方法,以显示延迟的幻灯片:

            var timer;

            var sliderFunc = function(){
                timer = $timeout(function(){
                    scope.next();
                    timer = $timeout(sliderFunc, 5000);
                }, 5000);
            };

            sliderFunc();

通过这个例子,一切都很好。

但是我想在第一个(1000)和其他幻灯片(5000)之间设置不同的延迟。 所以我试着设置“延迟”#39;这个例子动态参数:

            var timer;
            scope.timeout = 5000;

            var sliderFunc = function(){
                timer = $timeout(function(){
                    scope.next();
                    timer = $timeout(sliderFunc, scope.timeout);
                }, scope.timeout);
            };

            sliderFunc();

在第一次出现时,延迟是好的,但在接下来的步骤中,范围。超时'未定义。

有没有人知道如何解决它?


更新1:

如果我在第一次出现时检查我的代码,那么延迟' (等于上一个例子中的scope.timeout)等于' 5000'当我输入' slideFunc'时,在第二个函数和后续步骤中未定义:

delay to timeout method

更新2:

这是我的整个指令:

'延迟'应该在我的指令声明中设置。

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'
    };
});

1 个答案:

答案 0 :(得分:0)

使用双向绑定时,您不能只绑定标量值,例如整数。您必须绑定到对象的属性。这是因为它存储对象的引用的方式。基本上你在任何地方使用绑定都要确保有一个点。

例如

$scope.test = {
 v: [],
 z: 1000
}

<div ng-app="myApp.central.directives" ng-controller="ctrl">
    <slider list="test.v" delay="test.z"></slider>
</div>