停止$ timeout - AngularJS

时间:2015-01-10 08:29:35

标签: javascript angularjs

var app = angular.module('myapp', []);

app.controller('PopupCtrl', function($scope, $timeout){
$scope.show = 'none';


  $scope.mouseover = function(){
    console.log('Mouse Enter');
    $scope.show = 'block';
  };

  $scope.mouseout = function(){

       console.log('Mouse Leave');
        var timer = $timeout(function () {
          $scope.show = 'none';
        }, 2000);


  };

});

当鼠标悬停在按钮上时,会弹出一个弹出对话框。当我鼠标拖出时,弹出对话框将在两秒钟内隐藏。当我第二次鼠标悬停按钮时出现问题。即使我的光标仍然在按钮上,弹出对话框会在两秒钟内隐藏。当鼠标再次超过按钮时如何停止计时器?

1 个答案:

答案 0 :(得分:76)

$timeout服务返回可以使用$timeout.cancel()取消的承诺。在您的情况下,您必须在每个按钮鼠标悬停时取消超时。

DEMO

JAVASCRIPT

var app = angular.module('myapp', []);

app.controller('PopupCtrl', function($scope, $timeout){
  var timer;
  $scope.show = false;

  $scope.mouseover = function(){
    $timeout.cancel(timer);
    $scope.show = true;
  };

  $scope.mouseout = function(){
    timer = $timeout(function () {
      $scope.show = false;
    }, 2000);
  };

});