停止AngularJS 1

时间:2016-12-22 18:36:30

标签: javascript angularjs

我在学习Angular JS时正在进行一些测试。我有一些文本区域,当用户进入和退出时,它们通过Angular函数显示一些文本。 enter函数等待3秒,退出函数等待5秒。到目前为止这是有效的。

如果用户没有等待超时量,则任务的下一部分是取消将文本绑定到文本区域的功能。我很难接受那个,但我认为我需要使用承诺。

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

function checkTimeout() {
  console.log("Timeout is working...");
}

myApp.filter('rawHtml', ['$sce', function($sce){
   return function(val) {
   return $sce.trustAsHtml(val);
  };
}])

myApp.controller("MyCtrl", function($scope, $timeout){

$timeout(checkTimeout, 3000);

$scope.data = [{
  "id": 1,
  "act": ""
}, {
  "id": 2,
  "act": ""
}, {
  "id": 3,
  "act": ""
}, {
  "id": 4,
  "act": ""
}, {
  "id": 5,
  "act": ""
}, {
  "id": 6,
  "act": ""
}, {
  "id": 7,
  "act": ""
}, {
  "id": 8,
  "act": ""
}, {
  "id": 9,
  "act": ""
}];

$scope.enter1 = function(num) {
  $timeout (function(){num.act = " - enter";}, 3000 );
}

$scope.exit1 = function(num) {
  $timeout (function(){num.act = " - exit";}, 5000 );
}


})

HTML:

<body ng-app="myApp">
  <div ng-controller="MyCtrl" style="width:100%;margin:10px;">
      <p>How can I stop the functions enter1 and exit1 from binding text to the textarea if the user does not wait the 3 seconds (enter1) and 5 seconds (exit1) for them to execute?</p>
      <div style="float:right; width:49%;">
        <div ng-repeat="num in data" style="margin:3px;">
          <textarea ng-focus="enter1(num)" ng-blur="exit1(num)">{{ num.id }}{{ num.act }}</textarea>
        </div>
      </div>
  </div>
</body>

这是小提琴:https://jsfiddle.net/mediaguru/q3qt5frk/

2 个答案:

答案 0 :(得分:2)

$timeout构造函数返回一个值,可用于访问计时器。

var myTimer = $timeout(checkTimeout, 3000);

//Kill it
$timeout.cancel (myTimer);

答案 1 :(得分:0)

你必须清除所有的计时器。否则,将出现内存泄漏。如果调用定时器的元素被销毁,则清除定时器。在角度上,每个元素都有范围。如果特定元素的范围在我们必须清除所有计时器和事件的地方被破坏,$scope.$destroy()将触发。

var timers = new Array();
...
// add a timer to the array
timers.push(setTimeout('someFunc()', 1000));
...
// clear all timers in the array
for (var i = 0; i < timers.length; i++)
{
    clearTimeout(timers[i]);
}