2016-02-28 88 views
28

如何偵聽角度組件綁定更改並執行操作?如何使用Angular組件觀察組件綁定更改

angular.module('myapp') 
    .component('myComponent', { 
     templateUrl: 'some.html', 
     controller: MyController, 
     controllerAs: 'myCtrl', 
     bindings: { 
      items: '<' 
     } 
    }); 

現在當items變化我想用這個值來執行另一個動作,
我該怎麼辦呢?

回答

23

現在當項目發生更改時我想使用此值執行另一個操作, 我該怎麼辦?

但我想避免使用垂死$範圍

如果想用$scope,你可以使用屬性二傳手到例如檢測到任何變化:

class MyController { 
    private _items: string[] = [] 
    set items(value:string[]){ 
     this._items = value; 
     console.log('Items changed:',value); 
    } 
    get items():string[]{ 
     return this._items; 
    } 
} 

const ctrl = new MyController(); 
ctrl.items = ['hello','world']; // will also log to the console 

請注意,你不應該將其用於複雜的邏輯(原因:https://basarat.gitbooks.io/typescript/content/docs/tips/propertySetters.html

2

我發現了一種方法,但並不確定它是最有效的。首先引入$ scope作爲依賴關係,並將其設置爲this._scope或類似的構造函數。我已經在我的$onInit功能,那麼以下內容:

this._scope.$watch(() => { 
    return this.items; 
    }, 
    (newVal, oldVal) => { 
    // Do what you have to here 
    }); 

它的高度被這裏的答案啓發:Angularjs: 'controller as syntax' and $watch

希望它能幫助,這就是我要使用,直到有人告訴我,否則。

+0

謝謝您的回答!但我想避免使用垂死的$範圍 –

+1

是的,它感到骯髒,因爲「這個」變量應該是真正的範圍和觀看設置。我現在不得不在幾乎所有的組件中都這樣做!將值從空值切換到某些值可以正常工作,但只是更改觀看項目的內容仍然是個謎。 – Chris

0

目前,您不能使用沒有$ scope的角度觀察者,因爲更改檢測基於$ scope。即使你在HTML中使用表達式,它也會是delegate watch functionality to $scope

即使您創建了一些其他機制來觀察,您仍然需要記住手動解除觀察 - 並且使用$ scope自動完成。

5

這裏是basarat's answer的ES5.1版本:

function MyController() { 
    var items = []; 

    Object.defineProperty(this, 'items', { 
    get: function() { 
     return items; 
    }, 

    set: function(newVal) { 
     items = newVal; 
     console.log('Items changed:', newVal); 
    } 
    }); 
} 

使用Object.defineProperty()。支持所有主流瀏覽器和IE9 +。

48

您可以將$onChanges方法添加到控制器

$onChanges(changesObj)每當單向綁定更新被調用。 changesObj是一個散列,其中的鍵是已更改的綁定屬性的名稱,並且這些值是表單的一個對象。

以下示例句柄canChange更改事件。

angular.module('app.components', []) 
 
.component('changeHandler', { 
 
    controller: function ChangeHandlerController() { 
 
    $onChanges: function (changes) { 
 
     if (changes.canChange) 
 
     this.performActionWithValueOf(changes.canChange); 
 
    }; 
 
    }, 
 
    bindings: { 
 
    canChange: '<' 
 
    }, 
 
    templateUrl: 'change-handler.html' 
 
});

要求AngularJS> = 1.5.3和工作僅具有單向數據綁定(如在上面的例子)。

文檔:https://docs.angularjs.org/guide/component

參考:http://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html

+6

萬一它有助於其他人:請注意,這隻適用於較新的單向綁定語法(「<」),而不適用於使用「=」的更「傳統」雙向綁定。這是記錄,但容易錯過,因爲我學到了艱難的方式。 :-P –