定时器计数器指令

问题描述:

我写过这个例子hover counter指令在angularjs中。它可以工作,并将秒数写入控制台。它呈现“悬停我0”,但在计数时不更新数字。定时器计数器指令

angular.directive('countHoverTime', function() { 
    return { 
    link: function(scope, element, attributes) { 
     scope.seconds = 0; 
     var ticking = false; 

     var tickTock = function() { 
     scope.seconds++; 
     console.log('tick'); 
     if (ticking) { 
      window.setTimeout(tickTock, 1000); 
     } 
     } 

     $(element).hover(function() { 
     console.log('Hover In'); 
     scope.seconds = 0; 
     ticking = true; 
     tickTock(); 
     }, function() { 
     console.log('Hover Out'); 
     ticking = false; 
     console.log("Seconds: " + scope.seconds); 
     }); 

    } 
    }; 
}); 

和HTML

<p count-hover-time>Hover me! {{ seconds }} </p> 
+0

我喜欢apairet关于angularizing的评论,而不是jquery for .hover,但是我仍然需要调用scope。$ apply()来完成dom更新。 – linojon 2014-10-01 22:33:20

控制台日志前写这篇声明

scope.$apply(); 

对于更改模型反映在视图,你需要告诉角度说所做的更改。

您应该使用$scope.$apply();来做到这一点。

angular.module('so',[]) 
 

 
.directive('countHoverTime', function() { 
 
    return { 
 
    scope: true, 
 
    link: function(scope, element, attributes) { 
 
     scope.seconds = 0; 
 
     var ticking = false; 
 

 
     var tickTock = function() { 
 
     scope.seconds++; 
 
     scope.$apply(); 
 
     console.log('tick'); 
 
     if (ticking) { 
 
      window.setTimeout(tickTock, 1000); 
 
     } 
 
     } 
 

 
     $(element).hover(function() { 
 
     console.log('Hover In'); 
 
     scope.seconds = 0; 
 
     ticking = true; 
 
     tickTock(); 
 
     }, function() { 
 
     console.log('Hover Out'); 
 
     ticking = false; 
 
     console.log("Seconds: " + scope.seconds); 
 
     }); 
 

 
    } 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="so"> 
 
<p count-hover-time>Hover me! {{ seconds }} </p> 
 
</div>

问题是你正在使用jQuery来处理 '悬停' 事件。 Angular因此不知道scope.seconds已更改,因此无法相应地更新视图。如果你想继续使用jQuery的符号(即$(element).hover(function() {...,你必须调用scope.$apply()强行消化周期

我会通过改变

$(element).hover(...) 

一个角符号建议修复您:

element.hover(...) 

既然你包括jQuery的,这是等同$(element)但“angularized” 更多信息,请参见https://docs.angularjs.org/api/ng/function/angular.element