[英]Using $onChanges vs $onInit in angular component
使用Controller1
与Controller2
之间有区别吗?
angular.module('app', [])
.component('foo', {
templateUrl: 'foo.html',
bindings: {
user: '<',
},
controller: Controller1, //Or Controller2
});
function Controller1(){
this.$onInit = function(){
this.user = angular.copy(this.user);
};
this.$onChanges = function(changes){
if(changes.user && !changes.user.isFirstChange()){
this.user = angular.copy(changes.user.currentValue);
}
};
}
function Controller2(){
this.$onChanges = function(changes){
if(changes.user){
this.user = angular.copy(changes.user.currentValue);
}
};
}
当我可以在$onChanges
执行相同的操作并保存一些行时,为什么还要打扰$onInit
?
$onChanges
和$onInit
这种类型的初始化是否对某些其他类型的初始化更好?
$ onInit
在元素上的所有控制器均已构建并初始化其绑定之后(且在此元素上的指令的链接前和链接后),在每个控制器上调用。 这是放置控制器初始化代码的好地方。
$ onChanges
调用$ onChanges生命周期挂钩有几个原因。 首先是组件初始化,它在运行时将初始更改传递给对象,因此我们可以立即获取数据。 它被调用的第二个原因仅是发生在与父组件绑定的“ <”(单向数据绑定)和“ @”(用于评估的DOM属性值)发生变化时。 调用$onChanges
,您将获得一个可以挂入的特殊更改对象,我们将在接下来的部分中进行探讨。
实际的主要区别是,仅在指令初始化时调用$onInit
但在初始化期间以及<
和@
变量更改时将调用$onChanges
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.