【发布时间】:2018-02-01 22:50:45
【问题描述】:
在 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 V1.7 的发布,预先分配绑定到的选项已被弃用和删除。依赖于存在绑定的初始化逻辑应该放在控制器的
$onInit()方法中,保证在分配绑定后总是被调用。
标签: javascript angularjs