在我$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
。有什么建议么?
这是预期行为$watch
功能。
从文档
$watch(watchExpression, listener, [objectEquality]);
// watchExpression - can be `expression/function`
// listener - callback
// objectEquality - deepWatch
$watch
功能评估每个消化周期来看其expression
WRT $scope
。所以在第一种方法,你只是路过name
为string
,所以会发生什么,当消化周期踢,它试图评估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;
});
该watchExpression应设置为一个字符串(即使它已经是一个字符串)你试试这个?
var name = 'some value'
this.$scope.$watch('name', (oldVal, newVal) => {
console.log(oldVal, newVal);
console.log(this.$state.current.name);
});