> For the complete documentation index, see [llms.txt](https://xiaoxiami.gitbook.io/angularjs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xiaoxiami.gitbook.io/angularjs/scope/watchfang_fa.md).

# $watch方法

* 在digest执行时，如果watch观察的value与上次执行时不一样时，就会被触发
* AngularJS内部的watch实现了页面随model的及时更新
* $watch(watchFn,watchAction,deepWatch)

  watchFn:angular表达式或函数的字符串

  watchAction(newValue,oldValue,scope):watchFn发⽣生变化会被调⽤用

  deepWacth:可选的布尔值命令检查被监控的对象的每个属性是否发生变化
* $watch会返回一个函数，想要注销这个watch可以使用函数

**例子：**

index.html

```markup
<script src="//cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
<script type="text/javascript" src="app/index.js"></script>
<div ng-app="myApp">

        <div ng-controller="firstController">
            <input type="text" value="" ng-model="name"/>

            改变次数:{{count}}-{{name}}
        </div>
</div>
```

app/index.js

```javascript
var app = angular.module('myApp', []);

app.controller('firstController', function($scope){

    $scope.name = '张三';
    $scope.data = {
        name :'李四',
        count:20
    }
    $scope.count = 0;

    // 监听一个model 当一个model每次改变时 都会触发第2个函数
    $scope.$watch('name',function(newValue,oldValue){

        ++$scope.count;
        $scope.data.name = $scope.name;

        if($scope.count > 30){
            $scope.name = '已经大于30次了';
        }
    });

    $scope.$watch('data',function(){
        console.log($scope.data);
    },true)
```

以上代码解释：

1. 监听了$scope.name属性，当一个model每次改变时 都会触发第2个函数
2. 当输入框中的name改变，同时在函数中也改变了$scope.data对象的值，则会触发对data的监听，执行console.log($scope.data);
3. 注意$watch的最后一个属性，此处为true，则监听对象中的每个属性，只要有一个变化，则触发函数。

**效果**

![](/files/-LfnTGuAwOgjy9LwYIIq)

![](/files/-LfnTGuC92ZFd171CttH)
