Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller

    $scope.data = {
        home: {
            baseValue: "1",
            name: "home"
        },
        contact: {
            baseValue: "2",
            name: "contract"
        }
     // numerous other options
    };

How can I simplify the process of determining when the baseValue changes without having to loop through all the arrays?

Here is a snippet of my HTML:

<section class="content row" ng-repeat="item in data">
   {{item.name}}
   ....
</section>

I have tried using a general $watch function, but it requires me to iterate through each object individually.

$scope.$watch('data', function (newValue, oldValue, scope) {
 // code for comparing the arrays line by line
}, true);

Any suggestions on how to implement a more efficient $watch to only track changes in the baseValue property?

For related queries, check out these links:

  • AngularJS watch array of objects for data change
  • How to get an object that was changed in angularjs?
  • How to deep watch an array in angularjs?

UPDATE 1

If there are multiple objects in the data set, adding individual $watch functions for each object could become messy and inefficient. Any suggestions on improving this process?

$scope.$watch('data.home', function (newValue, oldValue, scope) {
 // logic for handling newvalue.baseValue
}, true);

$scope.$watch('data.contact', function (newValue, oldValue, scope) {
 // logic for handling newvalue.baseValue
}, true);
... // Add more individual `watch` functions

Answer №1

After analyzing your query, I suggest utilizing ngChange to monitor changes in the baseValue and then trigger the function accordingly.

Here is an example of how you can implement this:

<section class="content row" ng-repeat="item in data">
    Name: {{item.name}} <br/>
    BaseValue: <input type="text" ng-model="item.baseValue" ng-change="baseValueChange(item.baseValue)"/>
</section>

To handle a more advanced scenario where you need both the oldValue and newValue, you can check out this plunkr - http://plnkr.co/edit/hqWRG13gzT9H5hxmOIkO?p=preview

Here's how you would modify the HTML for that:

<section class="content row" ng-repeat="item in data">
    Name: {{item.name}} <br/>
    BaseValue: <input type="text" ng-init="item.oldBaseValue = item.baseValue" ng-model="item.baseValue" ng-change="baseValueChange(item.oldBaseValue, item.baseValue); item.oldBaseValue = item.baseValue"/>
</section>

And the corresponding Controller code:

$scope.baseValueChange = function(oldVal, newVal) {
    console.log("base value change", oldVal, newVal);
}

Answer №2

Observing an object attribute is possible.
An example of this can be seen below:

for(let property in $scope.data) {
  if($scope.data.hasOwnProperty(property)) {
    $scope.$watch("data['" + property + "'].baseValue", function(value, oldValue) {
      // Carry out desired actions
    });
  }
}

This code has not been executed, but the concept is straightforward.

Answer №3

In this particular situation, the only way to handle it is by utilizing multiple watches. Another approach is to use $watchCollection to monitor an array of object values. You can retrieve this array by using the Object.values method.

scope.$watchCollection(function() {
    return Object.values(obj);
}, function(newValues, oldValues) {
    // By monitoring all the values, you can track changes!
    // If you want a callback to be triggered with the object as an argument:
    if (angular.isFunction(scope.callback())) {
        scope.callback()(obj);
    }
});

Answer №4

This is the solution I used to solve the problem:

$scope.updateFields= function(){
    angular.forEach($scope.fields,function (value, key) {
        value.title = value.title.toLowerCase().replace(/\s+/g,'');
    })
};
$scope.$watch('fields', $scope.updateFields, 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

Tips for increasing a variable by one with each button click?

I have a simple JavaScript function called plusOne() that is designed to increment a variable by 1 each time a button is clicked, and then display the updated value on a webpage. However, I'm encountering an issue where the addition only occurs once. ...

Issue with breakpoints functionality in MUI v5 and React project

I've been attempting to utilize breakpoints for responsive design on my website, but unfortunately, it doesn't seem to be working correctly. Every time I implement a breakpoint, the entire page goes blank. Below is the code snippet I am working w ...

Utilizing PHP for XML exportation and fetching it through AJAX to integrate it into the DOM, unfortunately, the XML content remains invisible

I've encountered a strange issue with a PHP script that generates valid XML output. I'm trying to fetch this data using an Ajax XMLHttpRequest call in the browser. Although Firebug confirms that the Ajax request is successful and the XML is vali ...

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

Struggling with injecting $q into AngularJS?

Hey everyone! I've encountered a puzzling issue that I need help with. I'm attempting to inject the $q library into one of my controllers, but when I try to console.log() it, it shows up as "undefined". Oddly enough, I am successfully injecting ...

How can I restrict website access to only specific IP addresses?

I am looking to restrict access to certain IP addresses on a website, but the issue is that dynamic IPs keep changing based on the source of internet connection. Is there a method to determine the static IP of the computer rather than relying on the dyna ...

Ways to substitute numerous instances of a string in javascript

I have experience in developing websites using reactjs. I usually implement restAPI's with java and work with liferay CMS. In one of my projects, I created a shortcode for accordion functionality like this: ('[accordion][acc-header]Heading 1[/ac ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

Asynchronous functions within the next context

Hello there! I am trying to send the client's IP address from the frontend in a Next.js application to the backend. To retrieve the IP, I am using the following function: async function getIP() { var clientIP = await publicIp.v4(); ...

Pondering in AngularJS - what is the best way to alter the DOM during an AJAX call?

I'm completely new to AngularJS and trying to transition from a jQuery background. After reading through "Thinking in AngularJS if I have a jQuery background?" on Stack Overflow, I understand the concept but am struggling to implement it without depen ...

Retrieve the content of the nearest 'td' element using the '.closest()' method, then locate the desired

I am struggling to assign the value from a <td> to a variable. My approach involves utilizing the closest() and find() methods in jQuery to locate the desired <td>. Interestingly, when I use alert on the <td>, it displays the correct val ...

Getting the Featured Image from a Post Link in Wordpress: A Step-by-Step Guide

For my Wordpress project, I have a group of links leading to inner pages, each with their own featured image. These links are created using the menu feature in Wordpress. My goal is to allow users to click on these links and have the featured image from t ...

What is the best way to save the output of an asynchronous (AJAX) function in a variable?

This isn't a repeat query. I'm seeking assistance in locating a technical solution that hasn't been covered in the post How do I return the response from an asynchronous call? If .then() doesn't resolve the Promise, how can I pinpoint ...

The URIError occurred while attempting to decode the parameter '/December%2015,%' within the express framework

After setting up a middleware using the express framework that handles a URI with a date as a parameter, I encountered a small issue. app.get("/:date",function(req,res){ var result; var myDate=req.params.date if(moment(myDate).isValid()) ...

Leveraging multiple <Select /> tags in React with the help of react-select

I am working on creating multiple selection-inputs in React using react-select. How can I efficiently handle elements with multiple states? After generating elements through a loop (map), how can I determine the next value for the value prop? Is there a ...

Click and release file upload

I am working on creating a drag and drop upload feature where the user can drop files onto a div, and then click an upload button to send them to the server. I'm facing an issue with JavaScript not recognizing the variable fd. How can I pass that vari ...

Pass the form data to the next page with javascript in HTML

While working on a website for a power plant, I encountered some issues that require assistance. The main problem is that our client does not want to set up a database on their server. This means I can only use html, javascript, and a bit of php. There is ...

Typeahead.js is a powerful tool offered by Twitter that allows for easy auto-completion

I am currently working on a program that has the capability to search for specific university courses based on certain parameters. Within my large JSON object, there are 1360 objects, each consisting of around 20-30 parameters. However, I am only intereste ...

Taking out the modal element from the document object model, causing the animation

I am currently working on a project using Next.js, Typescript, and Tailwind CSS. Within this project, I have implemented a modal component with some animations. However, I encountered an issue where the modal does not get removed from the DOM when closed, ...

Encountered an error 'Unexpected token ;' while attempting to include a PHP variable in a jQuery AJAX call

Trying to execute a PHP script that updates a deleted field in the database when you drag a specific text element to a droppable area. Currently, here is the droppable area code: <div class="dropbin" id="dropbin" > <span class="fa fa-trash-o ...