# 4 watch types (include links to official AngularJS documentation)

$scope.$watch() method can be used for executing code after some scope value changed.

An useful example is the possibility to have "field recalculations" upon changing of their basic values.

$scope.$watch("net", function(newValue, oldValue){
    $scope.gross = newValue * 1.22;
})

this template has two variables (net and gross) without knowing the logic behind.

{ { gross } } instead of  net { { * 1.22 } }

AngularJS has four methods to record changes of an expression:

 - Reference $watch     -> $scope.$watch(expression, listener)

 - Deep equality $watch -> $scope.$watch(expression, listener, true)

 - Collection sequence $watch -> $scope.$watchCollection(expression, listener)

 - Array of references $watch   -> $scope.$watchGroup(array of expressions, listener) [NEW IN 1.3]

The first method simply checks there are no changes in object reference. The match is done using the JavaScript strict equal operator ===. It does not require any object copy, so its performance is fast.  The listener is applied when a primitive type variable changes value or when an object (or array) is replaced.

In the second case the object is copied by angular.copy and it is matched against the current value using angular.equals. The complexity of the matching function and its memory occupation due to the "deep copy", suggest to use it only if really needed. In this case the listener is applied for each modification of the interested value.

The third method is used to verify if elements or keys are added, removed or replaced inside element collections (objects, arrays, array-like objects). In this case only the reference to elements in the collection are stored and matched (via === operator) with the ones of current values.  This allows to verify addition, deletion or changes of elements inside a list, but not to detect possible changes of element values.  This method is used inside the directive ngRepeat.

The fourth method (only available in next release 1.3) is able to check any changes in elements of an array of expressions, using a reference $watch. For this method the same considerations made for "reference $watch" are applicable. So you can use it to create a value calculated based upon more values present in the scope.

$scope.$watch(["net", "tax"], function(){
    $scope.gross =  $scope.net * $scope.tax;
})

Antonello Pasella

Freelance Frontent Developer, PHP Expert , Website , Git home page , @apasella , Linkedin profile
15+ year experience in web programming, fucused on cross platform frontend and game development (even remote). Web enthusiast and game passionate, full stack programmer ready to dive into new projects. Top skills: AngularJS Phonegap PHP

All articles by Antonello Pasella

Comments

comments powered by Disqus

cloudparty

Follow Us