AngularJS $watchGroup

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

■ $watchGroup은 AngularJS 1.3에서 도입되었습니다. 첫번째 매개 변수가 관찰할 표현식의 배열이라는 점을 제외하면 $watch와 동일합니다.

$watchGroup(watchExpression, listener)

 
 
 

■ $watchGroup
리스너는 감시 된 변수에 대한 새 값과 이전 값이 있는 배열로 전달됩니다. 리스너는 watchExpressions 배열의 표현식이 변경 될 때마다 호출됩니다.

<script>
$scope.teamScore = 0;
$scope.time = 0;
$scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {
 if(newVal[0] > 20){
 $scope.matchStatus = 'win';
 }
 else if (newVal[1] > 60){
 $scope.matchStatus = 'times up';
 });
</script>

 
 
 

■ $watchGroup 예제

<!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.teamScore = 0;
       $scope.time = 0;

       $scope.changeTeamScore = function() {
              $scope.teamScore = $scope.teamScore + 1;
       }

       $scope.changeTime = function() {
              $scope.time = $scope.time + 1;
       }

    $scope.$watchGroup(['teamScore','time'], function(newVal, oldVal) {
       console.log( "new teamScore : " + newVal[0] + "\told teamScore : " + oldVal[0] );
       console.log( "new time : " + newVal[1] + "\told time : " + oldVal[1] );
       $("#log").text( "teamScore : " + $scope.teamScore + "\ttime : " + $scope.time);
    });

});
</script>
</head>
<body ng-controller="myAppCtrl">
       <h1>
              AngularJS $watchGroup<br/>
              <font color="red"></font>
       </h1>
       <button ng-click="changeTeamScore()">$watchGroup 테스트(teamScore+1)</button>
       <button ng-click="changeTime()">$watchGroup 테스트(time+1)</button>
       <hr/>
       <div id="log"></div>
</body>
</html>

 
 
 

■ $watch 예제 실행 결과

 
 
 

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다