在我的$onInit
中,我有一个$watch
:
public $onInit() {
const name = this.$state.current.name;
console.log(name);
this.$scope.$watch(name, (oldVal, newVal) => {
console.log(oldVal, newVal);
console.log(this.$state.current.name;
});
}
运行此代码时,oldVal, newVal
都是undefined
,并且this.$state.current.name
的值在$watch
的范围内和外部都相同。
当我运行不带name
表达式的代码时:
public $onInit() {
const name = this.$state.current.name;
console.log(name);
this.$scope.$watch((oldVal, newVal) => {
console.log(oldVal, newVal);
console.log(this.$state.current.name);
});
}
$watch
不断运行。 oldVal
是Scope {$id: 353, .... etc
,但是newVal
未定义。但是this.$state.current.name
现在在$watch
范围内更新了。
因此this.$scope.current.name
的值确实发生了变化。但是,当我将其用作$watch
中的表达式时,oldVal, newVal
都未定义,并且this.$state.current.name
内的$watch
未被更改。
好像我在watchExpression
中做错了什么。有什么建议吗?
答案 0 :(得分:2)
这是预期的行为$watch
函数。
来自文档
$watch(watchExpression, listener, [objectEquality]);
// watchExpression - can be `expression/function`
// listener - callback
// objectEquality - deepWatch
$watch
函数在每个摘要循环运行时评估其expression
和$scope
。因此,在第一种方法中,您只是将name
传递为string
,所以发生的事情是,当摘要循环开始时,它将尝试计算name
变量,该变量显然在{中不存在{1}},这就是您为每个$scope
评估获得undefined
值的原因。
在第二种方法中,您要将$watch
传递给function/callback
函数。这会在每个摘要循环运行时进行评估,这是错误的。您应该做的是,传递$watch
函数,该函数将返回callback
,然后只有this.$state.current.name
侦听器函数中才能获得所需的结果。
可以通过以下方法解决
$watch
答案 1 :(得分:0)
watchExpression应该设置为字符串(即使它已经是字符串) 你尝试过这个吗?
var name = 'some value'
this.$scope.$watch('name', (oldVal, newVal) => {
console.log(oldVal, newVal);
console.log(this.$state.current.name);
});