[AngularJS] $scope.$warchCollection

For the $watch in last article, we watch 'user.password', actually it is a string.

If you watch 'user', this object and we do something like:

function WatchCtrl ($scope) {

    $scope.$watch('user', function (newVal, oldVal) {
        console.log(newVal, oldVal);
    });

}

 

Actually it won't work.

Because, $watch without the third param is a reference watching. If we add the third param:

function WatchCtrl ($scope) {

    $scope.$watch('user', function (newVal, oldVal) {
        console.log(newVal, oldVal);
    }, true);

}

Then it lost value watching, but it is qiute expensive.

 

Actually we have another way to do that if what we are watching is an object by using $watchCollection:

function WatchCtrl ($scope) {

    $scope.$watchCollection('user', function (newVal, oldVal) {
        console.log(newVal, oldVal);
    });

}

 

posted @ 2014-11-13 07:25  Zhentiw  阅读(289)  评论(0编辑  收藏  举报