What is the best way to access the watchExpression within the listener of the $watch function?

Is there a way to access the watchExpression inside the listener function? My goal is to extract parameters from the watchExpression.

$watch(watchExpression, [listener], [objectEquality]);

Answer №1

Imagine you are interested in monitoring a model on scope that is defined as:

$scope.model = {firstName: 'John', lastName: 'Doe'};

There are 3 different ways to write the watcher below:

1. Watching Values

$scope.$watch('model', function(value) {
    // Listens for any changes to each item
    // The watcher will fire whenever firstName or lastName changes
    console.log(value.firstName); 
    console.log(value.lastName);
});

2. Monitoring New and Old Values

$scope.$watch('model', function(newVal, oldVal) {
    // Retrieves references of the new and old values of model
    // Normally checks for object reference equality
    // if (newVal === oldVal)
    console.log(newVal.firstName); 
    console.log(oldVal.firstName);
});

3. Directly Accessing from Scope

$scope.$watch('model', function() {
    // Listens for any changes to each item
    // Directly accesses from scope
    // It triggers only when a change occurs in the model
    console.log($scope.model.firstName); 
});

You can also deep watch an object if necessary, like so:

$scope.$watch('model', function(newVal, oldVal) {
   // Watches for changes deeply
}, true);

Deep watching/object equality tracks changes from the object graph to the root node. For instance, for a model such as:

$scope.model = { firstName: 'John', lastName: 'Doe', address: { zip: 1234 } };

The watch would also trigger for changes to zip in address.

You can watch not just an object but also specify a function whose return value can be monitored. The function takes the scope as a parameter by default:

$scope.$watch(function(scope) {
    return scope.model.firstName;
}, function(newVal, oldVal) {
    // Listens only to changes in the first name
    console.log(newVal.firstName); 
    console.log(oldVal.firstName);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The application is unable to access the getUserData property or method of the object

UserController.js var MyApp = angular.module('MyApp', []); MyApp.controller("LoginController", ["$scope", "$rootScope", function ($scope , dataService) { $scope.user = "example"; $scope.check ...

Adding Angular Components Dynamically to HTML Using a String, and Initializing with Bootstrap Framework

I am interested in achieving the following: Here is a snippet of code that I have: <body ng-app="MyApp"> <div id="content"><button onclick="addCode()">Add Code</button></div> </body> The function "addCode()" does this ...

Unable to transfer function to directive

I have set up a controller and directive as follows: angular.module('cms', ['TestMod']) .controller('MainCtrl', function() { this.refreshPage = function() { alert('Hello World'); }; }); angular.module(&apos ...

Angular Material fixed header and persistent footer

After struggling with this issue for quite some time, I think I may have come up with a solution. My goal is to have a fixed toolbar (navbar) along with a sticky footer that floats at the bottom of the main section. The challenge lies in making sure the fo ...

Transfer information to component displayed via $mdDialog

I am currently working with angular version 1.6.2 and angular-material version 1.1.4. Below is the implementation of a component I am using for $mdDialog: class CommentReplySettingsController { /** @ngInject */ constructor($mdDialog, $log) { this. ...

Issues have been encountered with the AngularJS Modal functionality when trying to populate data within an ng

Attempting to utilize a bootstrap modal for updating data in a list, the initial modal being used is to add a new item to said list. Successfully created the modal, triggered the ajax call, and returned the data to the main controller via the promise belo ...

Socket.io lost connection

Recently, I've encountered an issue with my chat application built using nodejs, Express, socket.io, and angular. Despite functioning well most of the time, it has a tendency to randomly disconnect after no more than 2 minutes, resulting in several ne ...

The term "angular" is not recognized or defined in

Upon executing gulp in the command line terminal, an error warning appears. I have included the angular.js file in the HTML code but can't pinpoint the issue. Here is the HTML code snippet: <!DOCTYPE html> <html lang="en" ng-app="confusionA ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

Anticipated reply should have been in the form of an object, however, it

Encountering an issue with resource.get(): "Error in resource configuration. Expected response to contain an object but got an array". Upon configuring the resource to expect an array, a different error arises: "Error in resource configuration. Expected ...

Another option instead of using $index for displaying serial numbers in ng-repeat

Looking to display a serial number for each table data entry being generated through the use of ng-repeat. The current code I have is as follows: <tr ng-repeat="usageRecord in applicationUsageDataForReport"> <td style="text-align: center">&l ...

ng-class in AngularJS not interacting with Scope method

I am in the process of creating a new application. Here is how my index.html file looks: <html ng-app='myApp'> <body ng-controller='mainController'> <div ng-view> </div> </body> </html> My m ...

The AngularJS $HTTP loop counter fails to update

When working with an HTTP service and binding JSON data to HTML, I implemented the following code: This function uses a 2-second timer to automatically fetch data whenever there is a change in the backend. function sampleDevices ...

Solution to determining if an object contains a certain value in AngularJS

Currently, I am working on avoiding duplicates and preventing the addition of empty items. In case I attempt to add an item with the same title (for example, Harry Potter) that already exists in $scope.libri, I want to prevent it from being added again. Is ...

What could be causing the delay in $q.all(promises).then() not waiting for the promises to complete?

Currently, I am tasked with utilizing AngularJS 1.5.5. My task involves making calls to multiple Rest-Services and handling the results simultaneously. $scope.callWebservices = function(){ let promises = { first: callFirstWebservice(), ...

Unable to dynamically change the value of the submit button using angular.js

I'm facing an issue with setting the submit button value dynamically using Angular.js. The code I've written below explains my problem. <body ng-controller="MainCtrl"> <input type="submit" value="{{ !model ? 'reset' : mod ...

Method in AngularJS Controller Instance

I have a unique angular js controller where I am structuring it for inheritance by other controllers. Rather than defining the function as a single one within the angular's controller function, I am taking a different approach: function SomeCtrl($ ...

Angular post request does not update the table

After displaying a table and a form on a page, I encountered an issue where the table does not update with new data when submitting the form. Even after refreshing the page, the new data is not reflected. As a newbie to Angular, I'm unsure of what exa ...

Error encountered in Node/Express application: EJS partials used with Angular, causing Uncaught ReferenceError: angular is not defined

I seem to be missing something important here as I attempt to incorporate ejs partials into a single-page Angular app. Every time I try, I encounter an Uncaught ReferenceError: angular is not defined in my partial. It seems like using ejs partials instead ...

Testing AngularJS components with header response verification

After a successful login on my web, the backend sends me an 'x-token'. In my frontend, I validate this token by setting $rootScope.authenticated = true;. If the token is missing from the header response for any reason, my frontend sets $rootScope ...