范围.带有$ timeout的$ watch [英] Scope.$watch with $timeout

查看:34
本文介绍了范围.带有$ timeout的$ watch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我在Angular中建立功能,但是我有一些问题.我有ng-model和example-directive,像这样.

Hey im building functionality in Angular but I have some problems. I have ng-model and example-directive, like this.

<input ng-model="model" type="text" class="form-control">
<div example-dir test="model"></div>

我想将我们的模型从输入传递到指令,并且该模型中的每个新值都开始$ timeout,但是第一个新值应开始$ timeout,但是每个下一个新值必须重新启动我们的$ timeout.

I want to pass our model from input to directive and each new val from this model start the $timeout, but the first new val should start the $timeout, but the each next new val have to restart our $timeout.

例如.当我们传递数据以输入$ timeout开始开始(对于eaxmple为1000毫秒)时,每个下一个数据都必须将$ timeout重新开始为0,然后重新开始.

For example. When we pass data to input the $timeout begin start(1000 ms for eaxmple) but the each next data have to restart our $timeout to 0 and begin start again.

有我的指令代码:

    function link(scope, element, attr) {
      
        scope.$watch('test',function(nval){
        var timeout;
        function incrementTimer(){
           //some stuff
        }
            if(nval){


                timeout = $timeout(incrementTimer, 1000);
                $timeout.cancel(timeout);

            }
        });
                    
            
    }

我不知道何时何地通过$ timeout并取消正常工作.感谢您的帮助.

I dont have idea where and when pass $timeout and cancel to working corectly. Thanks for help.

推荐答案

您正在做的是在每次迭代中重新声明 timeout 变量.在链接功能中声明超时,然后将其重置:

What you're doing is redeclaring the timeout variable with each iteration. Declare the timeout in the link function, and then just reset it:

link: function (scope) {
    function myFunc () { console.log('tick'); }      
    var timeout;

    scope.$watch(function () {
        return scope.test;
    }, function (newVal, oldVal) {
        if (timeout) {
            $timeout.cancel(timeout);
        }
        timeout = $timeout(myFunc, 1000);
    });
}

小提琴

这篇关于范围.带有$ timeout的$ watch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆