在角度组件中使用$ onChanges vs $ onInit

时间:2017-01-10 11:02:58

标签: javascript angularjs angular-components

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

当我在$onInit中执行相同的操作并保存一些行时,为什么要烦扰$onChanges

这种类型的初始化在$onChanges$onInit更好地用于其他类型的初始化吗?

1 个答案:

答案 0 :(得分:0)

<强> $的OnInit

在构造了元素上的所有控制器并初始化其绑定之后(在此元素上的指令的前置和后置链接函数之前),在每个控制器上调用。这是为控制器放置初始化代码的好地方。

<强> $ onChanges

出于几个原因调用$ onChanges生命周期钩子。第一个是在组件初始化时,它在运行时传递初始更改Object,因此我们可以立即获取数据。只有在&#39;&lt; (单向数据绑定)和&#39; @&#39; (对于已评估的DOM属性值),从父组件绑定。调用$onChanges后,您将获得一个可以挂钩的特殊更改对象,我们将在后续章节中进行探讨。

主要的实际差异是$onInit仅在指令初始化时调用,但$onChanges将在初始化期间以及<@变量发生变化时调用。

相关问题