【发布时间】:2015-12-23 10:54:25
【问题描述】:
我正在从 angular 1.x 迁移到 2.x,但我的大脑仍然在 angular 1.x 中思考,很抱歉提出愚蠢的问题。
当我的 范围变量 组件属性之一发生变化时,我需要采取一些措施。我找到了解决方案,但我认为应该有更好的解决方案
export class MyApp {
router: Router;
location: Location;
fixed: boolean = true;
private set isFixed(value:boolean) {
this.fixed = value;
//TODO: look here
console.log('isFixed changed', value);
}
private get isFixed():boolean {
return this.fixed;
}
constructor(router: Router, location: Location) {
this.router = router;
this.location = location;
}
}
查看console.log('isFixed changed', value); 行,这就是我需要的,它正在工作。但是我通过声明getter 和setter 做到了,但是没有更好的方法来观察变量吗?就像在角度 1.x 中是 $scope.$watch?
我认为我的组件代码应该是这样的
export class MyApp {
router: Router;
location: Location;
isFixed: boolean = true;
//TODO: $watch for isFixed change {
console.log('isFixed changed', value);
// }
constructor(router: Router, location: Location) {
this.router = router;
this.location = location;
}
}
【问题讨论】:
-
您的代码中的
isFixed是如何更改的?什么在修改值?
标签: javascript angular