Observing the full object (deep watch) using AngularJS

In this scenario, we have a

angular-resource variable / object
within the scope that serves as form data:

    $scope.form = {
              name: 'bob', 
              email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99b969bb99b969b8ad79a9694">[email protected]</a>'
    }

I have implemented a watch function to monitor changes in the name variable.

    $scope.$watch('form.name', function(newVal) {
        if(newVal) {
            alert(newVal)
        }
    });

How can I set up a watch to detect any changes in fields such as name, email, or any other potential values within scope.form?

The ultimate goal is to toggle the 'save' button on the form based on whether the user has made any modifications.

Answer №1

When using $watch(), there is an additional parameter that allows for checking object equality (deep watch).

$scope.$watch('form', function(newVal) { //watch the entire object
    if(newVal) {
        alert(newVal);
    }
}, true); //set to "true" for deep watch.

In this case, both methods yield the same outcome: View live demo here (click). However, it's important to note that $watchCollection only performs a shallow watch and won't monitor nested changes.

$scope.$watch('form', function(newForm, oldForm) {
    console.log(newForm.name);
}, true);

Alternatively: (not a deep watch)

$scope.$watchCollection('form', function(newForm, oldForm) {
    console.log(newForm.name); 
});

Answer №2

Ever since AngularJS 1.1.x, the recommended method for monitoring multiple values within an array or properties of an object is through the use of $watchCollection. You can learn more about it here: http://docs.angularjs.org/api/ng.$rootScope.Scope

$scope.$watchCollection('form', function(newValues, oldValues) {
    console.log('*** Watch has been triggered. ***');
    console.log('New Names :', newValues);
});

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

Using Material UI Autocomplete for Categorical Selections in a ReactJS Application

Using MUI Autocomplete and Formik, I'm looking to organize items into categories. If an item doesn't have any sub_accounts, then it should not display a header label. Check out the example here: https://mui.com/material-ui/react-autocomplete/#gro ...

Javascript is failing to fetch the desired text

I'm in the process of tweaking the code found at 'http://jsfiddle.net/vivin/RjqUf/' to allow users to select a line or word from a PDF. I've added the following JavaScript snippet at the end of the existing code: $(".textLayer").mouseu ...

Restrict Fineuploader to uploading only one file at a time

Is there a way to restrict the number of files that can be dropped in the bucket to just one file? I've tried using the validation directive and setting the itemLimit attribute to 1, but it doesn't seem to work as expected. Here's the code s ...

Send the NameSpace to the object and store it in the local storage

Hey there! I've developed an Android application that accesses the device certificates to retrieve specific information (APPCID). handleCertificate(appId) { OData.defaultHttpClient = sap.AuthProxy.generateODataHttpClient(); this.factory.connectionDa ...

Use javascript to implement pinch zoom functionality in a canvas element by allowing users to zoom from the

Can I zoom in from the point where I pinch instead of the center of the image within a Canvas element? Here is an example of what I am looking for, but I need the same effect within a canvas. When I zoom in, I want it to be centered on the point where I z ...

Utilizing mongoose data for rendering in express

Currently utilizing the Hackathon-starter framework, I am looking to incorporate the user's name from the database into the render title property in express.js. The specific file that requires modification can be found here ...

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

Removing an element from a JSON array

I'm having trouble figuring out how to delete an element from a JSON array when the user clicks on a delete button. I suspect there might be an issue with the PHP script. javascript.js $(".delete").on('click', function(e){ var dele ...

Unexpected behavior from vuelidate triggered on blur

I have implemented vuelidate for form validation. My goal is to validate user input either when they move to the next input field or click outside of the current one. <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$ ...

Steps for removing all inline styles within an element:1. Access the element's

I have a group of span elements containing texts generated by tinymce. <span class="ArticleSummary"> This content is produced using a text editor and may include various inline styles. </span> Typically, this text includes numerous inline s ...

Error encountered when trying to export XLS file from HTML with style formatting using AlaSql

Alasql is proving to be quite useful for exporting XLS files from JavaScript, although I have not been able to find a comprehensive tutorial on it. While attempting to export XLS directly from HTML, I encountered an issue with adding cell formatting to th ...

Invoke a React component within a conditional statement

There is a function for exporting data in either csv or xls format based on an argument specifying the type. The functionality works flawlessly for xls but encounters issues with csv. Here's the code snippet: const exportFile = (exportType) => { ...

How can I uniquely identify and edit individual cells within an ng-grid using the bgColor property?

I need some clarification regarding Angularjs ng-grid. Is there a way to distinguish between the edit-cell and non-edit-cell in ng-grid? Perhaps using different background colors? ...

Formatting phone numbers in AngularJS using ng-grid

Curious if anyone has come across this issue while using the ng-grid component to display data. I have a column with phone numbers and I'm wondering if there is a simple way to format them as (123)-123-1234. This is what my ng-grid code currently lo ...

Ways to add a substantial quantity of HTML to the DOM without relying on AJAX or excessive strings

Currently, I am looking to update a div with a large amount of HTML content when a button on my webpage is clicked. The approach I am currently using involves the .html() method in JQuery, passing in this extensive string: '<div class="container-f ...

Combining AngularJS and Java to create dynamic web applications in HTML5 mode

I'm developing a platform that uses AngularJS for the frontend and Java with Jersey for the backend. However, I've encountered an issue when trying to eliminate the "#" from the URL using $locationProvider.html5Mode(true);. When I click on a li ...

How do you retrieve an element using its tag name?

Just delving into the world of API's here. Working on a project involving loading a DIV with a bunch of links that I need to repurpose. Managed to disable the default onclick function, now trying to figure out how to save the "innerHTML" attribute of ...

Identifying a page refresh in Angular 2

Just a quick question. I am working on an angular2 application. Is there a way to detect if the user refreshes the page using a typescript component? PS: I tried using onbeforeunload, but it didn't work for me. ...

JavaScript guide: Converting an array structured by tuples into a multidimensional array

I'm working with an array, X[(i,j,l)], which is indexed by 3-dimensional tuples where i and j range from 1 to n, and l ranges from 1 to "layers". This binary array consists of elements that are either 0 or 1. The array was generated as a result of so ...

What is the best approach for integrating HTML and JavaScript code into Flutter mobile platforms?

For the past 4 months, I've been immersing myself in Flutter without any prior experience in Javascript. My goal is to utilize the Soundcloud HTTP API to create a user-interactive app. However, I've hit a roadblock when it comes to integrating JS ...