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 :)
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
And for more specifically you should not use
click
event of document then you should namespace your event just by doingclick.testing
then you code will look much smarter. Because at time you do$document.unbind('click')
that will removeclick
event fromdocument
Updated
Code