angularJS1筆記-(2)-$watch方法監聽變量的變化

html:javascript

<!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:html

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);
});

最終結果:java

相關文章
相關標籤/搜索