Watch an object with AngularJS's $scope and detect and respond only to changes in its property values

Currently, I am monitoring scope changes using a simple watch like this:

$scope.$watch('myObject', function(newValue, oldValue) {
    if (newValue !== oldValue) {
       return newValue;
    }
}, true);

In this case, myObject is an ordinary object with multiple properties. My goal is to only detect and return the specific property that has been modified, such as myObject.changedProperty.

My preference is to keep track of the entire object without setting up separate watches for each individual property. Is there a way to achieve this?

Your insight on this matter would be highly appreciated!

Answer №1

You can achieve the desired functionality with $watchCollection in AngularJS. ($rootScope.Scope)

$watchCollection(obj, listener);

When using $watchCollection, it shallow watches the properties of an object and triggers when any property changes (including array items and object map properties). The listener callback is then executed.

The obj collection is monitored through a standard $watch operation, checking for additions, removals, or movements on each call to $digest(). The listener is triggered whenever a change occurs within the obj, such as adding, removing, or moving items in an object or array.

Answer №2

Appreciate all the assistance, folks. Here's how I tackled it:

$scope.$watch('myObj', function(newVal, oldVal) {
    for (var property in myObj) {
        if(newVal[property] !== oldVal[property]) {
           return newVal[property];
        }
    }
}, true);

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

Issue with ng-cloak not resolving flicker on button in Chromium; strangely, ng-cloak CSS doesn't apply as expected

Here is a snippet of my HTML code: <button type="button" class="btn btn-primary ng-cloak" ng-click="ctrl.add(ctrl.userProfile.username)" ng-hide="ctrl.userProfile.added">Add</button> The code above is a part of the larger HTML document shown ...

Having trouble administering $httpBackend injection

Currently, I am utilizing Angular 1.5 to create mocked services for my current project by referring to this helpful example: https://embed.plnkr.co/qsmx8RUmQlXKkeXny7Rx/ Here is a snippet of the code that I have developed so far: function() { 'use ...

What steps should I take to modify the URL using the SELECT tag?

Having a bunch of SELECT tags in place <select id="url"> <option id="url1" >url 1</option> <option id="url2" >url 2</option> </select> <button onclick="go()">GO</button> Followed by the associated scrip ...

Is the history object automatically passed to child components within the Router in react-router-dom?

Is it normal for the Router component to automatically pass down the history object to child components? To showcase this concept, consider the following code snippet: App.js ; const App = () => { return ( <> <h1>Hello</h1&g ...

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...

Problem with targeting the .prev() and closest() class of a text input box

Could you please review This Demo and advise why I am unable to select the first .fa class before the text box #name ? This is what I have been trying: $(this).prev().closest(".fa").addClass("err"); within this code block <div class="row"> & ...

What steps should I take to ensure that elements beneath a div are made visible?

I've been working on a unique project to create a website with "hidden text" elements. One of the cool features I've developed is a circular div that follows my mouse cursor and flips all text below it using background-filter in both CSS and Jav ...

Manipulating JSON arrays in Javascript - Remove an object from the array

I'm looking to remove an element from a JSON objects array. Here's the array: var standardRatingArray = [ { "Q": "Meal", "type": "stars" }, { "Q": "Drinks", "type": "stars" }, { "Q": "Cleanliness", "type": " ...

Require checkboxes in AngularJS forms

Currently, I have a form that requires users to provide answers by selecting checkboxes. There are multiple checkboxes available, and AngularJS is being utilized for validation purposes. One essential validation rule is to ensure that all required fields a ...

Why do we recreate API responses using JEST?

I've been diving into JavaScript testing and have come across some confusion when it comes to mocking API calls. Most tutorials I've seen demonstrate mocking API calls for unit or integration testing, like this one: https://jestjs.io/docs/en/tuto ...

Similar to Angular ui-router 1.0.3, what is the equivalent function for reloadOn

After updating to UI-router v1.0.3 from v0.3.2, I noticed that the reloadOnSearch feature has been removed from the stateConfig. I'm having trouble finding the equivalent of reloadOnSearch in v1.0.3. It doesn't seem to be documented anywhere. A ...

What methods are most effective for showcasing Flash messages within Express.js?

I have a Node.js app in the EJS framework and I am new to JavaScript. Could someone please advise me on the correct way to set flash messages in Node.js? Below is my code which is throwing an error: C:\Users\sad\Desktop\Node Applica ...

Is there a return value for the GEvent.addListener(...) function?

I have a question regarding GEvent.addListener(map, "click" function(){...}). I couldn't find any information about what it returns in the callback function in the GMaps reference. Can you provide some insight on this? The documentation mentions two p ...

Tips for modifying VueJS's <slot> content prior to component instantiation

I am working with a VueJS component called comp.vue: <template> <div> <slot></slot> </div> </template> <script> export default { data () { return { } }, } </script> When I ...

VueJS waits until the loop is complete before executing a re-render

Check out this VueJS code snippet: new Vue({ el: '#app', data: { tiles: [ { isActive: false }, { isActive: false }, { isActive: false }, { isActive: false }, { isActive: false } ] }, methods: { ...

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

Several radial progress charts in JavaScript

While attempting to recreate and update this chart, I successfully created a separate chart but encountered difficulties with achieving the second progress. The secondary chart <div id="radial-progress-vha"> <div class="circle-vha ...

Encountering a React clash while integrating Material UI

Upon trying to utilize the AppBar feature in Material UI version 0.16.6, I encountered the following error: Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created within a c ...

Global JavaScript functionality is disrupted by the webpack runtime chunk

After embedding a VueJs application into an existing site with its own set of JavaScript libraries, I encountered an issue. The runtime chunk in my application is calling the existing scripts from the site, resulting in multiple event listeners being added ...

Timeout causes failure in AngularJS jasmine promise testing

I need help testing my login controller, here is the structure of it: describe('LoginController', function() { beforeEach(module('task6')); var $controller, LoginService; beforeEach(inject(function(_$controller_, _LoginSe ...