Angularjs 在 ES6 中绑定的组件和 $watch
Angularjs Component and $watch with Binding In ES6
您好,我正在开发 AngularJS 组件,需要帮助如何在 Constructor() 中使用 $watch,如下所示,我附上了我的代码结构。
import template from './Mypage.component.html';
export const MyComponent = {
template,
bindings: {
myData: '<'
},
controller: class MyController {
constructor($scope) {
$scope.$watch(() => this.myData, newVal => {
this._myFunction();
});
}
}
使用$onChanges()
方法代替$scope.$watch()
class MyController {
constructor() {
// Your constructor...
}
$onChanges(changedObj){
// Expect myData changes
console.log(changedObj)
}
}
更多信息here
您应该在 $inject
数组中添加 $scope
依赖项并在构造函数中使用它应该可以。但请找到以下建议。
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();
}
}
您好,我正在开发 AngularJS 组件,需要帮助如何在 Constructor() 中使用 $watch,如下所示,我附上了我的代码结构。
import template from './Mypage.component.html';
export const MyComponent = {
template,
bindings: {
myData: '<'
},
controller: class MyController {
constructor($scope) {
$scope.$watch(() => this.myData, newVal => {
this._myFunction();
});
}
}
使用$onChanges()
方法代替$scope.$watch()
class MyController {
constructor() {
// Your constructor...
}
$onChanges(changedObj){
// Expect myData changes
console.log(changedObj)
}
}
更多信息here
您应该在 $inject
数组中添加 $scope
依赖项并在构造函数中使用它应该可以。但请找到以下建议。
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();
}
}