随着 AngularJS V1.7 的发布,预先分配绑定(bind)到的选项已被弃用和删除:
Due to 38f8c9, directive bindings are no longer available in the constructor.
To migrate your code:
- If you specified
$compileProvider.preAssignBindingsEnabled(true)
you need to first migrate your code so that the flag can be flipped tofalse
. The instructions on how to do that are available in the "Migrating from 1.5 to 1.6" guide. Afterwards, remove the$compileProvider.preAssignBindingsEnabled(true)
statement.
Due to bcd0d4, pre-assigning bindings on controller instances is disabled by default. We strongly recommend migrating your applications to not rely on it as soon as possible.
Initialization logic that relies on bindings being present should be put in the controller's
$onInit()
method, which is guaranteed to always be called after the bindings have been assigned.— AngularJS Developer Guide - Migrating from v1.5 to v1.6 - $compile
必须将代码移至
$onInit
Life-Cycle Hook 时的用例是什么? ?我们什么时候可以将代码留在 Controller 构造函数中?
最佳答案
代码必须移入 $onInit
函数,当它依赖于绑定(bind)时,因为这些绑定(bind)在 this
中不可用在构造函数中。它们在组件类的实例化之后被分配。
例子:
你有一个这样的状态定义:
$stateProvider.state("app", {
url: "/",
views: {
"indexView": {
component: "category"
}
},
resolve: {
myResolve: (someService) => {
return someService.getData();
}
}
});
可以绑定(bind)
myResolve
的结果像这样到您的组件:export const CategoryComponent = {
bindings: {
myResolve: "<"
},
controller: Category
};
如果您现在退出
this.myResolve
在 constructor
在 $onInit
你会看到这样的东西:constructor() {
console.log(this.myResolve); // <-- undefined
}
$onInit() {
console.log(this.myResolve); // <-- result of your resolve
}
因此,您的构造函数应该只包含如下构造代码:
constructor() {
this.myArray = [];
this.myString = "";
}
每个 Angular 特定的初始化和绑定(bind)或依赖使用都应该在
$onInit
中。
关于angularjs - 何时使用 AngularJS `$onInit` 生命周期 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51273521/