0

I would like have a on listener something like below for all controllers which are instantiated. And, I don't want to include this expression in all of my controllers. I just wanted to set this listener on all new scopes created in angualr js application.

$scope.$on('somebroadcastedevent', function someEvent() {

});

How can I accomplish?

squiroid
  • 13,809
  • 6
  • 47
  • 67
raghu
  • 59
  • 1
  • 9

1 Answers1

1

Override ngController directive.

module.directive('ngController', function () {
   return {
      link: function (scope) {
          // register the listener here. 
          scope.$on('somebroadcastedevent', function someEvent() {

          });
      }
   }
})
Vinay K
  • 5,562
  • 1
  • 18
  • 27
  • Hi Vinay thanks for the answer. How about extending a base controller as suggested in this link?http://stackoverflow.com/q/16539999/1847031 – raghu Mar 28 '15 at 11:58
  • This approach will not create any inheritance. To inject common properties in all the controllers this approach is very simple. – Vinay K Mar 28 '15 at 13:16
  • Just a note, this approach will not work when controller is instantiated using $controller. – Vinay K Mar 28 '15 at 13:17