如何在$ watch函数的监听器中获得watchExpression?

时间:2014-03-22 02:24:57

标签: angularjs watch

$watch(watchExpression, [listener], [objectEquality]);

如何在监听器中获取watchExpression?我想解析watchExpression以获取参数。

1 个答案:

答案 0 :(得分:1)

我们假设您想要在范围内观看模型,该范围定义为:

$scope.model = {firstName: 'John', lastName: 'Doe'};
观察者可以用以下3种不同的方式编写:

<强> 1.value

$scope.$watch('model', function(value) {
    //watches any change to each item
    //everytime the watcher will fire when firstName or lastName changes
    console.log(value.firstName); 
    console.log(value.lastName);
});

2.新旧价值

$scope.$watch('model', function(newVal, oldVal) {
    //You get reference of new and old value of model
    //normally object reference equality is checked
    //if (newVal === oldVal)
    console.log(newVal.firstName); 
    console.log(oldVal.firstName);
});

3.直接来自范围

$scope.$watch('model', function() {
    //watches any change to each item
    //access from scope directly
    //You are inside only when anything has changed on model
    console.log($scope.model.firstName); 
});

作为附加组件,您还可以根据需要深入观察对象:

$scope.$watch('model', function(newVal, oldVal) {
   //watch changes
}, true);

深度监视/对象相等性将跟踪从对象图到根节点的更改。例如,对于像这样的模型:

$scope.model = { firstName: 'John', lastName: 'Doe', address: { zip: 1234 } };

观察也会触发zipaddress的更改。

不仅可以观看对象,还可以指定可以观看其返回值的函数。该函数默认使用scope作为参数:

$scope.$watch(function(scope) {
    return scope.model.firstName;
}, function(newVal, oldVal) {
    //Only watch the first name
    console.log(newVal.firstName); 
    console.log(oldVal.firstName);
});