Execute a function when the value of a property in an array of objects is modified

Here is an example of my array object.

$scope.arr = [{"A":"a","B":"b"},{"A":"c","B":"d"},{"A":"e","B":"f"},{"A":"g","B":"h"}];

I am looking to trigger a function whenever the value of property "A" changes, specifically to count all instances where "A" has a non-empty value. The following scenarios should trigger this function:

  • If the value of "A" changes in a newly added object to the array.
  • If an object is removed where the property "A" contains a value.
  • If a value is added to an empty "A" in an object.
  • If an existing value in "A" is emptied in an object.

I have looked into Angular watch documentation and understand that it may be a possible solution. However, I am struggling with how to watch for the specific property("A") within any object of the array.

Any help on this matter would be greatly appreciated.

If there is no viable solution in Angular, I am also open to alternative solutions using underscore.js.

Answer №1

When working with AngularJS, you can utilize the $scope.$watch function:

$scope.$watch("arr",function (newVal,oldVal){
    console.log("The value has changed from "+oldVal+" to "+newVal);
},true);

However, this approach can be quite costly.

For pure Javascript, there exists an unconventional implementation known as object.watch which is sourced from here

/*
 * object.watch polyfill
 *
 * 2012-04-03
 *
 * By Eli Grey, http://eligrey.com
 * Public Domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

// object.watch
if (!Object.prototype.watch) {
    Object.defineProperty(Object.prototype, "watch", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function (prop, handler) {
            var
              oldval = this[prop]
            , newval = oldval
            , getter = function () {
                return newval;
            }
            , setter = function (val) {
                oldval = newval;
                return newval = handler.call(this, prop, oldval, val);
            }
            ;

            if (delete this[prop]) { // can't watch constants
                Object.defineProperty(this, prop, {
                      get: getter
                    , set: setter
                    , enumerable: true
                    , configurable: true
                });
            }
        }
    });
}

// object.unwatch
if (!Object.prototype.unwatch) {
    Object.defineProperty(Object.prototype, "unwatch", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function (prop) {
            var val = this[prop];
            delete this[prop]; // remove accessors
            this[prop] = val;
        }
    });
}

Answer №2

To achieve this functionality, you can utilize the $watch method.

For example:

$scope.$watch("arr",function (newVal,oldVal){
     angular.forEach(newVal,function (val,index){
         if(oldVal.indexOf(val)== -1){
                 //your code
              }
        }) 

},true);

The third parameter 'true' in this case is used for performing a deep check.

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

Improving the efficiency of ajax/javascript is necessary as the delay in data retrieval is too significant. There must be a more effective approach to this

Utilizing ajax requests to populate modal popup windows with user-filled data has been my current method. These popup windows, designed as div layouts, are controlled by jquery for showing and hiding. However, there seems to be a noticeable delay in this p ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...

Is it possible to define a variable within a JavaScript function and then access it outside of the function?

I have a Node.js application where I need to define a variable inside a function and access its value outside the function as well. Can someone provide guidance on how to achieve this in my code? var readline = require('readline'); var rl = read ...

Using PHP to convert JSON data into the Google Chart API

I am facing an issue with parsing my PHP generated JSON array into a Google chart. I have integrated JQuery, but for some reason, I am struggling to parse the JSON data. I execute a MySQL query to fetch data from the database. Then, I encode the query resu ...

Can an object serve as a property name for another object?

Can this be achieved using JavaScript? I'm attempting to assign the property name of an object as a "HTMLInputElement": var el = $('#something').get(0), obj = {}; obj[el] = 'some random data'; Unfortunately, it ...

Navigating through a vue array with the assistance of index

I am working with an object that contains multiple arrays. All of these arrays have the same number of items, and I am looking to iterate through them in order to display their data. My specific question is whether it is appropriate for me to iterate throu ...

Is it possible to merge two jQuery functions into a single one?

Here are my two jQuery functions: $(document).on('change','.states',function(){ //on change of select }); $(document).on('click','.date_control',function(){ //on click of input .date_control }); I am lookin ...

Guide to designing a personalized mesh in THREE.JS

I've inquired about this and received the following response: var geom = new THREE.Geometry(); var v1 = new THREE.Vector3(0,0,0); var v2 = new THREE.Vector3(0,500,0); var v3 = new THREE.Vector3(0,500,500); geom.vertices.push(new THREE.Vertex(v1)); ...

Why is it that a website is loading at a snail's pace on Angular?

Working on my college project has been going smoothly, except for one issue with slow loading times. It's frustrating how long it takes to load. I suspect that there might be an error in the deployment process or something else causing the delay. The ...

How to incorporate a delay in ng-repeat using AngularJS

Currently, I am facing an issue with my ng-repeat block. In this block, I am generating elements based on data received from an ajax request, which sometimes causes a delay due to latency. Within the same block, I have implemented a filter to remove unwant ...

grid causing images to display incorrectly in incorrect positions

My project consists of 3 component files and a CSS file, but I am facing an issue where the Tiles are slightly off in their positioning towards the top left corner. Although no errors are being thrown, upon using the view grid feature in Firefox, it is ev ...

Is it possible for Node.js to manipulate video files?

I'm curious about the compatibility of Node.js with videos, specifically in terms of editing rather than just playing them. My ultimate goal is to be able to reverse videos online. While Java seems like a solid option so far, I am drawn to Node.js for ...

Error: The function `res.status` is unsupported

I've been working on a function to allow uploading images to imgur through my express API (nodejs), but I'm running into an issue when calling a function that returns a promise: TypeError: res.status is not a function at uploadpicture.then T ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...

Merging scripts to minimize HTTP requests - The Takeover of the Body Swappers

For my website design, I've implemented the Invasion Of The Body Switchers script from brothercake.com. This script involves loading three separate js files in the header. I'm looking to optimize my site by reducing the number of HTTP requests a ...

Develop a form that relies on multiple requests made through AJAX

I am attempting to create a form that requires 2 ajax calls. The first call retrieves information about a ranking that is then displayed in the form using the following code: $.ajax({ method: "GET", url: base_url + "/ranking/getranktoedit/" + rank ...

Encountering a Build Error in Angular 6 when running the command "ng build --prod"

NG -V Angular CLI: 6.2.3 Node: 8.11.3 OS: darwin x64 Angular: 6.1.9 ... animations, common, compiler, core, forms, http ... platform-browser, platform-browser-dynamic, router Package Version ------------------------------------- ...

Why won't my Java servlet code execute?

included the directory structure To facilitate adding two numbers and displaying the result upon clicking a submit button, I developed a straightforward Java servlet. This servlet retrieves the necessary information when called. The development environmen ...

What is the importance of using mutations, setters, and getters for effectively managing state?

As I delve into the world of state management in Vue.js, I am finding it to be quite complex and confusing with all the different methods such as mutations, getters, and setters. Why can't we just change data directly? Wouldn't that make the code ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...