AngularJS $watchCollection

참고(구글번역)
Understanding $watch(), $watchgroup() and $watchCollection() methods of scope
(http://www.dotnettricks.com/learn/angularjs/understanding-watch-watchgroup-and-watchcollection-methods-of-scope)
 
 
 

■ $watchCollection는 객체의 속성을 감시하고 속성이 변경 될 때마다 발생합니다. 객체를 첫 번째 매개 변수로 사용하고 객체의 속성을 감시합니다.

$watchCollection(obj, listener)

 
 
 

■ $watchCollection
리스너는 객체의 아무 속성이나 변경될 때마다 호출됩니다.

<script>
$scope.names = ['shailendra', 'deepak', 'mohit', 'kapil'];
$scope.dataCount = 4;

$scope.$watchCollection('names', function (newVal, oldVal) {
 $scope.dataCount = newVal.length;
});
</script>

 
 
 

■ $watchCollection 예제

<!DOCTYPE html>
<html ng-app="myApp">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8">
<head>
<title></title>
<script src="/js/angularjs/1.5.6/angular.js"></script>
<script src='/js/jquery/jquery-1.11.0.min.js'></script>
<script>
var myApp = angular.module("myApp",[]);
myApp.controller("myAppCtrl", function($scope){

       $scope.person = {
              name : "",
              age  : 0,
              score: 0
       };

       $scope.changeName = function() {
              $scope.person.name = "mirinae";
       }

       $scope.changeAge = function() {
              $scope.person.age = $scope.person.age+1;
       }

       $scope.changeScore = function() {
              $scope.person.score = $scope.person.score+10;
       }

    $scope.$watchCollection('person', function(newVal, oldVal) {
       console.log( "newVal : " + JSON.stringify(newVal) + "\told oldVal : " + JSON.stringify(oldVal) );
       $("#log").text( "person : " + JSON.stringify(newVal));
    });

});
</script>
</head>
<body ng-controller="myAppCtrl">
       <h1>
              AngularJS $watchCollection<br/>
              <font color="red"></font>
       </h1>
       <button ng-click="changeName()">$watchCollection 테스트(change name)</button>
       <button ng-click="changeAge()">$watchCollection 테스트(change age)</button>
       <button ng-click="changeScore()">$watchCollection 테스트(change score)</button>
       <hr/>
       <div id="log"></div>
</body>
</html>

 
 
 

■ $watchCollection 예제 실행 결과