Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Controller Instantiated Multiple Times

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?

like image 580
Shamoon Avatar asked Apr 14 '26 01:04

Shamoon


1 Answers

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() {
      ...
    };
  });
like image 59
Caio Cunha Avatar answered Apr 17 '26 13:04

Caio Cunha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!