I am having a hard time understanding why the code in my directive won't stop running even after I have changed states and the dom element I am restricting the directive to is no longer in an available view. In the below code example, if I start at the home page, the document.addEventListener function will not run on mouse down, which is what I would expect. Then when I get the the our_purpose state, where the div with a class of "test" resides, the event fires on click as expected. However, when I navigate back to the home state, the event listener still persists.
How do I make it so all the code that lives within my test directive can be removed and no longer work ... Is there a way to restart everything from the directive so that it no longer exists until you are in that view?
This is a simplified version of my working code, but there is a lot of functionality in the real directive that causes issues when you are in the other state.
var app = angular.module('app', ['ui.router']);
app.directive("test", function() {
return {
scope: true,
transclude: false,
controller: 'OurPurposeCtrl',
restrict:"C",
link:function( scope, elem, attr) {
function testThis() {
console.log("still running the directive");
}
function init() {
document.addEventListener( 'mousedown', testThis, false );
}
init();
}
}
});
app.config(['$stateProvider','$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'landing',
templateUrl: 'views/landing.html'
})
.state('our_purpose', {
controller: 'OurPurposeCtrl',
url: '/our-purpose',
templateUrl: 'views/our-purpose.html'
})
}
]);