1. 程式人生 > >Angular中使用 watch監聽object屬性值的變化

Angular中使用 watch監聽object屬性值的變化

                     

Angular中的$watch可以監聽屬性值的變化,然後並做出相應處理。
常見用法:

$scope.$watch("person", function(n, o){    //todo something...})
  • 1
  • 2
  • 3

但是對於一個物件中的某個屬性值變化時,$watch似乎不管用了。
示例程式碼:

<body>    <div ng-controller="mainCtrl">        <input id="myText" type="text" ng-model="person.name"/>        <h2>{{person}}</h2
>
        <h2>Status:
{{status}}</h2>    </div>    <script>    angular.module('myApp', [])        .controller('mainCtrl', function ($scope) {            $scope.person = {                name:"allen",                age:21            }            $scope.$watch("person", function
(n, o){
                //取消第一次載入時的監聽響應                if(n == o){                    return;                }                $scope.status = "changed"            })    })
</script></body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

我們為輸入框綁定了person物件的name屬性,然而當我們改變輸入框的值時候,{{person}}確實改變了,然而並沒有出現我們想要的change字元。

效果:
這裡寫圖片描述

我們需要為$watch方法額外新增一個true引數,使之達到我們想要的效果:

$scope.$watch("person", function(n, o){    if(n == o){        return;    }    $scope.status = "changed";},true)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

$watch方法完整的使用方式是這樣的:

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

第一個是監聽的引數名稱,剩下兩個可選引數分別為處理函式和是相等比較的方式,對於後者文件如是說:Compare for object equality using angular.equals instead of comparing for reference equality. 即是否使用angular.equals方法進行比較。

如此效果變為:
這裡寫圖片描述