简体   繁体   English

在角度分量中使用$ onChanges与$ onInit

[英]Using $onChanges vs $onInit in angular component

Is there a difference between using Controller1 vs Controller2 ? 使用Controller1Controller2之间有区别吗?

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);
      }
    };
}

Why should I bother with $onInit when I can just do the same this in $onChanges and save some rows? 当我可以在$onChanges执行相同的操作并保存一些行时,为什么还要打扰$onInit

Is this type of initialization better in $onChanges and $onInit better for some other kind of initialization? $onChanges$onInit这种类型的初始化是否对某些其他类型的初始化更好?

$onInit $ onInit

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). 在元素上的所有控制器均已构建并初始化其绑定之后(且在此元素上的指令的链接前和链接后),在每个控制器上调用。 This is a good place to put initialization code for your controller. 这是放置控制器初始化代码的好地方。

$onChanges $ onChanges

The $onChanges lifecycle hook gets called for a few reasons. 调用$ onChanges生命周期挂钩有几个原因。 The first, is on component initialisation, it passes down that initial changes Object at runtime, so we can grab our data straight away. 首先是组件初始化,它在运行时将初始更改传递给对象,因此我们可以立即获取数据。 The second reason it gets called is only when changes occur to '<' (one-way databinding) and '@' (for evaluated DOM attribute values) that are being bound to from the parent component. 它被调用的第二个原因仅是发生在与父组件绑定的“ <”(单向数据绑定)和“ @”(用于评估的DOM属性值)发生变化时。 Once $onChanges gets called, you'll get a special changes Object back that you can hook into, which we'll explore in the upcoming sections. 调用$onChanges ,您将获得一个可以挂入的特殊更改对象,我们将在接下来的部分中进行探讨。

The primary practical difference is $onInit will be called only on the directive initialisation but $onChanges will be called during initialisation and when < and @ variables changes. 实际的主要区别是,仅在指令初始化时调用$onInit但在初始化期间以及<@变量更改时将调用$onChanges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM