【问题标题】:Reset Angular Countdown Directive重置角度倒计时指令
【发布时间】:2014-03-24 17:33:27
【问题描述】:

我有一个倒计时指令,一旦模式警告用户他们的会话即将超时,它就会从元素中的初始值倒计时到 0。一旦倒计时达到零,系统会提示用户退出或继续。如果他们点击继续,最终如果他们得到相同的会话到期警告模式,则计数器为 0。我无法完全弄清楚如何重置计数器指令,而不只是返回它并在所有未来的警告中停止它。这是我现在拥有的代码。

.directive("ndCountdown", function($timeout, $compile){
    return{
        restrict: 'A',
        link: function(scope, element, attrs){
            var countdown = function(){
                var timer = element.find('strong');
                for(var i = 0; i < timer.length; i++){
                    var secs = parseInt(timer.text(), 10) - 1;
                    if(secs >= 0){
                        timer.text(secs);
                    } else{
                        //reset the element to the original value
                        //stop the timeout in this session but have it continue to 
                        //work in future dialogs.
                    }
                }
                $timeout(countdown, 1000);
            }
            countdown();
        }
    }
});

【问题讨论】:

    标签: javascript angularjs timeout


    【解决方案1】:

    第一步是保存原来里面的变量。然后只有在你没有结束时才运行超时。

    .directive("ndCountdown", function($timeout, $compile){
    return{
        restrict: 'A',
        link: function(scope, element, attrs){
            var timer = element.find('strong'),
                MAX   = parseInt(timer.text());
            var countdown = function(){
                for(var i = 0; i < timer.length; i++){
                    var secs = parseInt(timer.text(), 10) - 1;
                    if(secs >= 0){
                        timer.text(secs);
                        $timeout(countdown, 1000);
                    } else{
                        timer.text(MAX);
                    }
                }
            }
            countdown();
        }
    }
    });
    

    现在,如果您需要能够重新启动它,您可能希望从您的控制器传达一些信息。也许像这样的 $broadcast。 一定要注入 $rootScope

    $rootScope.$broadcast('event:start-countdown');
    

    然后在您的指令中,在链接函数的末尾添加它,并注入 $rootScope。再次。

    $rootScope.$on('event:start-countdown', function() {
        countdown();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      相关资源
      最近更新 更多