$手表唯一的工作没有watchExpression

问题描述 投票:2回答:2

在我$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, newValundefinedthis.$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, .... etcnewVal是不确定的。但this.$state.current.name现在更新$watch范围内。

所以this.$scope.current.name的值不改变。但是当我使用的是作为$watcholdVal, newVal表达都是不确定和this.$state.current.name不在$watch内改变。

它看起来像我做错事的watchExpression。有什么建议么?

angularjs watch
2个回答
2
投票

这是预期行为$watch功能。

从文档

$watch(watchExpression, listener, [objectEquality]);
// watchExpression - can be `expression/function` 
// listener - callback
// objectEquality - deepWatch

$watch功能评估每个消化周期来看其expression WRT $scope。所以在第一种方法,你只是路过namestring,所以会发生什么,当消化周期踢,它试图评估name变量,这显然不存在$scope,这是你对每个获得undefined值的原因$watch评价。

而在第二个方法你传递function/callback$watch功能。其评估每个消化周期来看,这是不对的。你应该做的是,通过callback函数将返回this.$state.current.name,在$watch监听功能,那么只有您会收到预期的效果。


它可以使用下面来解决

this.$scope.$watch(() => {
   return this.$state.current.name
}, (oldVal, newVal) => {
    console.log(oldVal, newVal);
    console.log(this.$state.current.name;
});

0
投票

该watchExpression应设置为一个字符串(即使它已经是一个字符串)你试试这个?

var name = 'some value'
this.$scope.$watch('name', (oldVal, newVal) => {
    console.log(oldVal, newVal);
    console.log(this.$state.current.name);
});

Documentation

© www.soinside.com 2019 - 2024. All rights reserved.