2017-06-01 58 views
1

您好我正在AngularJS組件上工作,需要幫​​助如何使用$ watch內的Constructor()如下我附加了我的代碼結構。

import template from './Mypage.component.html'; 
export const MyComponent = { 
template, 
bindings: { 
    myData: '<' 
}, 
controller: class MyController { 
    constructor($scope) { 
    $scope.$watch(() => this.myData, newVal => { 
    this._myFunction(); 
    }); 
    } 
} 

回答

0

您應該添加$scope依賴內部$inject陣列,並用它在構造函數應該工作。但請在下面找到建議。

controller: class MyController { 
    $inject = ['$scope']; 
    constructor($scope) { 
    $scope.$watch(() => this.myData, newVal => { 
     this._myFunction(); 
    }); 
    } 
} 

我們都知道$watch確實每個消化週期將觸發以更新頁面上data bidnings,它是壞的性能的原因。相反,您可以使用angularjs組件的$onChanges生命週期鉤,以便在綁定值發生變化時纔會觸發。

controller: class MyController { 
    constructor($scope) {} 
    $onChanges(newVal) { 
    this._myFunction(); 
    } 
} 
0

使用$onChanges()方法,而不是$scope.$watch()

class MyController { 
    constructor() { 
    // Your constructor... 
    } 

    $onChanges(changedObj){ 
    // Expect myData changes 
    console.log(changedObj) 
    } 
} 

更多信息here