简体   繁体   English

带有TypeScript的AngularJS 1:将$ rootScope.on放在控制器中的什么位置?

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

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)... :\\ 但这没有任何意义,因为constructor只被调用一次(每次启动)...:\\

You put $on in your controller and the you also $off using your controller's scope's $destroy event. 您将$on放入控制器中,并且还使用控制器的示波器的$destroy事件$off

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

Events 大事记

$destroy $ 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. 请注意,在AngularJS中,还有一个$ destroy jQuery事件,该事件可用于在从DOM中删除元素之前清除DOM绑定。

Also: 也:

Personal Opinion: Events can make your code quite hard to reason about. 个人观点:事件会使您的代码难以推理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM