在 AngularJS 的 Controller 中,可以利用 $scope 的 $watch 來即時監控資料的正確性

<script>
    function AlbumCtrl($scope) {
        $scope.age = 13;
        $scope.$watch('age', function(){
            if ($scope.age > 20) {
                alert('Too old');
            }
        });
    }
</script>
<div ng-controller="AlbumCtrl">
    <input ng-model="age">
    <span ng-bind="age"></span>
</div>

監聽 object

$scope.info= {
    name: 'Johnson'
};

$scope.$watch('info', function() {
    console.log('modify');
}, true);

另外也可以透過 $watchCollection 或 $watchGroup(1.3後才有) 兩個函式可以使用

$watchCollection 用來監測 collection

$scope.names = ['Johnson', 'Tom'];

$scope.$watchCollection('names', function() {
    console.log($scope.names);
});

$watchGroup 用來監測多個變數

$scope.names = 'Johnson';
$scope.age = 25;

$scope.$watchGroup(['names', 'age'], function() {
    console.log($scope.names);
    console.log($scope.age);
});
Categories: AngularJS