Explain Codes LogoExplain Codes Logo

$watch an Object

javascript
watching-objects
angularjs
performance-optimization
Alex KataevbyAlex Kataev·Mar 10, 2025
TLDR

AngularJS's $scope.$watch is your tool of choice for monitoring changes in objects. Establish a deep watch by setting the third parameter to true. This tracks modifications in all properties of the object, including nested ones.

$scope.$watch('obj', (newVal, oldVal) => { // You could place console.log here, but who logs in production, right? 🙊 }, true); // This enables a deep watch, not shallow like my ex... just kidding.

Watching objects efficiently

Okay, time for some trade secrets. Deep watching with $scope.$watch can be a massive memory hog with large objects. It's like trying to keep track of all your ex's feelings – exhaustive and performance-killing. To preserve your application's performance, use $scope.$watchCollection for first level properties.

$scope.$watchCollection('obj', (newVal, oldVal) => { // This tracks changes only on first-level properties of 'obj' });

Debugging with $watch

You know how debuggers say, "console.log is my best friend"? Well, they are not wrong. Place console.log inside your $watch callbacks for debugging. Monitor how your values change, and where you left your sanity.

$scope.$watch('obj', (newVal, oldVal) => { console.log('Object update: ', oldVal, '🔄', newVal); }, true);

Handling complex data structures

Got complicated data? Tame the beast with services or factories. Restricting data mutation to specific areas simplifies data management, making it as simple as reheating yesterday's pizza.

// Here's how you implement a data service. You're welcome. app.service('DataService', function() { let data = { // Place your data structure here }; this.getData = function() { return angular.copy(data); }; this.updateData = function(newData) { angular.copy(newData, data); }; });

Using timestamps for data change detection

When caching gets dicey, or objects play hide and seek with their update schedule, try timestamps. They're like breadcrumbs in a forest, showing you the way.

$scope.lastModified = Date.now(); $scope.$watch('data', (newValue) => { $scope.lastModified = Date.now(); }, true);

Why use $watchCollection over $watch

$watch is your Sherlock, inspecting all levels. $watchCollection is the neighborhood watch, eyeing the immediate vicinity. For the sake of performance, use $watchCollection when you only need to track immediate properties.

angular.equals' affair with $watch Remember, $watch and angular.equals are from the same planet. But you can use angular.equals manually to have more control over comparison logic.

$scope.$watch('obj', (newVal, oldVal) => { if (!angular.equals(newVal, oldVal)) { // You can act only when values are truly different } }, false);

The risks and rewards of $watch

  • Memory leaks: Stay tidy – clean up watches on the $destroy event.
  • Large arrays: Tread lightly. Deeply watching large arrays is an expensive endeavor.
  • Working with big applications: For such heavy lifting, contemplate using RxJS or ES6 Proxies.