AngularJS 1 with TypeScript: where in controller to put $rootScope.on?

1.4k Views Asked by At

Service

export class RandomServiceName implements ng.IServiceProvider {
  /* @ngInject */
  constructor(private $rootScope: ng.IRootScopeService) {
  }

  public $get(): RandomServiceName {
    return this;
  }

  doStuff() {
      this.$rootScope.$broadcast('hello', 'world');
  }
}

Controller

import {RandomServiceName} from './random_service_name.ts';

export class RandomController {
  /* @ngInject */
  constructor(private $rootScope: ng.IRootScopeService,
              private $log: ng.ILogService,
              private RandomServiceName: RandomServiceName) {
      this.RandomServiceName.doStuff();
      this.$rootScope.$on('hello', (event: ng.IAngularEvent, data: string) =>
          this.$log.info(`Event '${event.name}' caught with data ${data}`)
      );
  }
}

But that doesn't make sense, because the constructor is only called once (per initiation)... :\

1

There are 1 best solutions below

0
basarat On

You put $on in your controller and the you also $off using your controller's scope's $destroy event.

More : https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$destroy

Events

$destroy

Broadcasted when a scope and its children are being destroyed. Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

Also:

Personal Opinion: Events can make your code quite hard to reason about.