2016-03-25 53 views
1

嗨我在Angular中構建函數,但我遇到了一些問題。 我有ng-model和example-directive,像這樣。

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

我想從輸入指令,並從這個模型每個新VAL通過我們的模型開始$超時,但第一個新的VAL應該啓動$超時,但每下一新的val必須重新啓動我們的$超時。

例如。當我們傳遞數據以輸入$ timeout begin start(eaxmple爲1000 ms)時,但每個下一個數據都必須將$ timeout重新啓動爲0並開始重新啓動。

還有就是我的指令代碼:

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

 
      } 
 
     }); 
 
        
 
      
 
    }

我沒有想法何時何通$暫停和取消corectly工作。 感謝您的幫助。

回答

2

你正在做的是在每次迭代時重新聲明timeout變量。聲明超時的鏈接功能,然後就重置:

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

Fiddle

+1

感謝驚人的簡單的答案! –

+0

你能告訴我如何檢查範圍嗎$ watch值是空的嗎? –

+0

@JanKowalski你有'newVal'和'oldVal'。如果你想更新的值檢查「if(!newVal){// value is empty}」 –

相關問題