$ watch仅在没有watchExpression的情况下工作

时间:2019-02-12 10:02:24

标签: angularjs watch

在我的$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不断运行。 oldValScope {$id: 353, .... etc,但是newVal未定义。但是this.$state.current.name现在在$watch范围内更新了。

因此this.$scope.current.name的值确实发生了变化。但是,当我将其用作$watch中的表达式时,oldVal, newVal都未定义,并且this.$state.current.name内的$watch未被更改。

好像我在watchExpression中做错了什么。有什么建议吗?

2 个答案:

答案 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);
});

Documentation

相关问题