In angularJS, I want to do something, when the area is destroyed, when I searched in the line, I went to this page: http://www.bennadel.com/blog/2548-Don-t-Forget-To-Cancel-timeout- Timers-In-Your-destroy-Events-In-AngularJS.htm? & _ = 0.5475860409906698 # comments_44655
I changed the code a bit, as shown below, but $ destroy does not seem to be fired. after closing the browser tab or switching to another URL, I canβt see anything in the console window.
Can anyone help?
Thanks in advance.
<!DOCTYPE html>
<html class="ng-scope" ng-app="Demo" ng-controller="DemoController"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>
Don't Forget To Cancel $timeout Timers In Your $destroy Events In AngularJS
</title>
<style type="text/css">@charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\:form{display:block;}</style></head>
<body>
<h1>
Don't Forget To Cancel $timeout Timers In Your $destroy Events In AngularJS
</h1>
<p>
<a href="#" ng-click="toggle()">Toggle Section</a>
</p>
<div ng-switch="section">
<p class="ng-scope" ng-switch-when="happy" bn-directive="">
Oh sweet!
</p></div>
<script type="text/javascript" src="http://bennadel.imtqy.com/JavaScript-Demos/vendor/jquery/jquery-2.0.3.min.js">
</script>
<script type="text/javascript" src="http://bennadel.imtqy.com/JavaScript-Demos/vendor/angularjs/angular-1.0.7.min.js">
</script>
<script type="text/javascript">
var app = angular.module( "Demo", [] );
app.controller(
"DemoController",
function( $scope ) {
$scope.section = "happy";
$scope.toggle = function() {
if ( $scope.section === "happy" ) {
$scope.section = "sad";
} else {
$scope.section = "happy";
}
};
}
);
app.directive(
"bnDirective",
function( $timeout ) {
function link( $scope, element, attributes ) {
var timer = $timeout(
function() {
console.log( "Timeout executed", Date.now() );
},
2000
);
timer.then(
function() {
console.log( "Timer resolved!", Date.now() );
},
function() {
console.log( "Timer rejected!", Date.now() );
}
);
$scope.$on(
"$destroy",
function( event ) {
$timeout.cancel( timer );
console.log( "Timer Canceled!", Date.now() );
}
);
}
return({
link: link,
scope: false
});
}
);
</script>
</body></html>
source
share