I have an Angular controller loaded in a view:
<div ng-controller="MyCtrl">
<p ng-bind-html="content"></p>
</div>
This partial is loaded into different views, and as a result the controller gets instantiated multiple times. In the controller, I'm detecting for location change:
angular.module('MyApp')
.controller('HintCtrl', function ($scope, $rootScope) {
$rootScope.$on('$locationChangeSuccess', function () {
alert("HI");
});
});
Each time I change my location, this fires once for each time the controller was ever loaded. How can I have this run only once?
The point is that Controllers are not singleton. You gonna have one new instance for each of the elements.
What you can do, is to use this on a service, and this one is singleton.
You could do something like this:
angular.module('MyApp')
.controller('HintCtrl', function ($scope, Alerter) {
Alerter.doSomething();
})
.service('Alerter', function($rootScope) {
$rootScope.$on('$locationChangeSuccess', function () {
alert("HI");
});
this.doSomething = function() {
...
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With