簡體   English   中英

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

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

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

當我可以在$onChanges執行相同的操作並保存一些行時,為什么還要打擾$onInit

$onChanges$onInit這種類型的初始化是否對某些其他類型的初始化更好?

$ onInit

在元素上的所有控制器均已構建並初始化其綁定之后(且在此元素上的指令的鏈接前和鏈接后),在每個控制器上調用。 這是放置控制器初始化代碼的好地方。

$ onChanges

調用$ onChanges生命周期掛鈎有幾個原因。 首先是組件初始化,它在運行時將初始更改傳遞給對象,因此我們可以立即獲取數據。 它被調用的第二個原因僅是發生在與父組件綁定的“ <”(單向數據綁定)和“ @”(用於評估的DOM屬性值)發生變化時。 調用$onChanges ,您將獲得一個可以掛入的特殊更改對象,我們將在接下來的部分中進行探討。

實際的主要區別是,僅在指令初始化時調用$onInit但在初始化期間以及<@變量更改時將調用$onChanges

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM