'How to unload AngularJS directive when changing templates

I have a web app built with AngularJS and it includes various routes/controllers/views/etc.

Several views require directives that I include. I've noticed though that when I change the route and a new template is loaded the directives from the old template continue to be run. Simply creating a directive that logs to console you'll continue to have it logging when the new route is loaded.

Is there a way to avoid this? It seems a bit of a waste of memory.



Solution 1:[1]

You need to unbind events bound to within the directive.

For example, if you had a resize event bound to the window you would do the following:

$scope.$on('$destroy',function() {
    angular.element($window).unbind('resize')
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1