angularJS1笔记-(2)-$watch方法监听变量的变化

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div ng-app="myApp">
    <div ng-controller="firstController">
      <input type="text" ng-model="name">{{name}}
    </div>
</div>
<script type="text/javascript" src="../../vendor/angular/angularJs.js"></script>
<script type="text/javascript" src="app/index.js"></script>
</body>
</html>

 js:

angular.module('myApp',[]).controller('firstController',function ($scope) {
    $scope.name = "dyk";
    $scope.count = 2;

    $scope.data = {
        name:'李四',
        count:20
    }
    //观察name 当一个model值发生改变的时候 都会触发第二个函数
    $scope.$watch('name',function (newValue, oldValue) {
        $scope.count++;
        if($scope.count>30){
            $scope.name = '已经大于30次了';
        }
    });

    $scope.$watch('data',function () {
        //指定第三个参数为true 意思是说如果触发了data对象里的任何一个值就可以触发监听

    },true);
});

最终结果:

 

 

  

posted @ 2017-04-28 16:09  My Way!  阅读(4002)  评论(0编辑  收藏  举报