为什么要在AngularJS中使用$ onInit? [英] Why to use $onInit in AngularJS?
问题描述
在AngularJS中,如果没有该功能就可以执行相同的初始化,那么$onInit
函数的目的是什么?
In AngularJS, what is the purpose of the $onInit
function if I can do the same initialization without that function?
例如:
module.component("myComponent", {
...
controller: function() {
const $ctrl = this;
$ctrl.$onInit = () => {
$ctrl.var1 = "hello";
$ctrl.var2 = { test: 3 };
}
}
});
也可以这样:
module.component("myComponent", {
...
controller: function() {
const $ctrl = this;
$ctrl.var1 = "hello";
$ctrl.var2 = { test: 3 };
}
});
在某些情况下需要$onInit
吗?
推荐答案
每个 AngularJS文档
在元素上的所有控制器均已构建并初始化其绑定之后(且在该元素上的指令的pre& post链接功能之前),在每个控制器上调用.
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).
这给您两个保证:
- 此元素上的所有控制器均已构建
- 前置&此元素的发布链接功能尚未执行
与您的第一种方法相反,后者无法保证所有这些事实(尽管第二种方法很可能是 ).
In contrast to your first method, where neither of these facts are guaranteed (though the second one is highly probable).
此外,就样式和可读性而言,它使潜在的阅读者/审阅者非常清楚这是您作为开发人员打算在初始化此控制器时运行的代码.
In addition, as a matter of style and readability, it makes it very clear to a potential reader/reviewer that this is code that you as the developer intended to run upon initialization of this controller.
这篇关于为什么要在AngularJS中使用$ onInit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!