"$onInit" 是比 "activate" 更有效的方式来激活 angularJS 中的 "controller" 吗?

Is "$onInit", more efficient way than "activate" to activate "controller" in angularJS?

我是 angularJS 的新手,想为我的项目实现高效的功能,但卡在了 $onInitlife cycle hook)和 activate() 之间。

在控制器中创建一个 activate() 函数并直接调用它与使用 AngularJS.

提供的 $onInit() 生命周期钩子完全不同

来自https://docs.angularjs.org/guide/component#component-based-application-architecture

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

所以基本上 activate() 函数将在您的控制器构建后立即调用。 $onInit() 函数将在 所有绑定成功绑定后被调用 。因此,如果您尝试在构造函数中访问绑定变量,它们将不会被初始化。

activate() 的使用是一个见仁见智的问题,因为它是一些固执己见 风格指南推荐的风格。

另一方面,$onInit Life-Cycle Hook$compile 服务调用。

来自文档:

Life-cycle hooks

Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the directive:

  • $onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

AngularJS $compile Service API Reference - Life-Cycle Hooks