How to delete functions of previous instances of controller?

108 views Asked by At

I have a simple angularjs controller referenced as someCtrl and it contains the following code:

function testing() {
    console.log("Hello there.");
}

$document.on('click', function(e) {
    testing();
});

this.getView = function(value) {
    return viewService.getView(value);
};

this.setView = function(value) {
    viewService.setView (value);
};

this.destroy = function() {
    $state.reload('default_state');
};

When click event happens, testing() function executes and something gets logged to the console. Later my default viewA changes to viewB using a service and ng-show directive:

<div ng-show="someCtrl.getView('viewA')">
   Content
</div>

<div ng-show="someCtrl.getView('viewB')">
    <a ng-click="someCtrl.setView('viewA'); someCtrl.destroy();">go to viewA</a>
</div>

Then, when click event happens, testing() function executes twice or even more times per click if I change view again and again... Why does that happen? Are two instances of controller alive? Doesn't $state.reload kill properties of one instance of controller? I would really appreciate some help :)

1

There are 1 answers

0
Pankaj Parkar On BEST ANSWER

Events are not cleared from DOM automatically though they are attached from controller. You could do that by ensuring the event bind only once. you could unbind it first & then bind it again.

Code

$document.unbind('click');//ensure it will bind once
$document.bind('click', function(e) {
    testing();
});

And for more specifically you should not use click event of document then you should namespace your event just by doing click.testing then you code will look much smarter. Because at time you do $document.unbind('click') that will remove click event from document

Updated

Code

$document.unbind('click.custom');//ensure it will bind once
$document.bind('click.custom', function(e) {
    testing();
});

NOTE

Bad practice to put DOM event listeners inside angular controller, better create a controller that would extend this functionality.