javascript - 为什么要在 AngularJS 中使用 $onInit?

标签 javascript angularjs

<分区>

在 AngularJS 中,如果我可以在没有该函数的情况下进行相同的初始化,那么 $onInit 函数的目的是什么?

例如:

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 docs

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).

这给了你两个保证:

  1. 此元素上的所有 Controller 均已构建
  2. 该元素的前后链接函数尚未执行

与您的第一种方法相反,在第一种方法中,这些事实都不能得到保证(尽管第二种方法极有可能)。

此外,就风格和可读性而言,它让潜在的读者/审阅者非常清楚,这是您作为开发人员打算在初始化此 Controller 时运行的代码。

关于javascript - 为什么要在 AngularJS 中使用 $onInit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573034/

相关文章:

当项目从 ng-repeat 中移除时,AngularJS UI Bootstrap popover outsideclick 触发器关闭 popover

javascript - 在 HTML 标签上动态插入 angularJS contextMenu

javascript - jQuery 在初始页面加载时重新加载 javascript 资源

javascript - 带有 ES6 和 webpack 的 AngularJS 1.7 给出错误 : Uncaught TypeError: Cannot read property 'module' of undefined

javascript - 在下拉导航中将文本向左移动

javascript - Webpack 类优先级

javascript - 计算每种类型事件的相关性

javascript - Angular promise - POST 请求

javascript - 错误 : Package exports for tslib do not define a valid '.' target

javascript - 不变违规 : Invariant Violation: Text strings must be rendered within a <Text> component