Matt McDonald
Matt McDonald

Reputation: 5050

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.

Upvotes: 3

Views: 2069

Answers (1)

Matt McDonald
Matt McDonald

Reputation: 5050

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')
})

Upvotes: 6

Related Questions