3

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?

1
  • Maybe you should handle the event in a parent controller. This is how angular works and it's coherent that each controller sees the event. Commented Dec 11, 2013 at 15:12

1 Answer 1

6

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() {
      ...
    };
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.