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

Issues Arising When Using $scope Variable as Datasource in Kendo UI Grid with AngularJS

I have tried multiple tips and tricks from various sources, but I still can't seem to solve my problem. My goal is to replace a trNgGrid with the Kendo UI Grid. The trNgGrid functions differently as it retrieves its data from a $scope variable named ...

ReactJS - When a child component's onClick event triggers a parent method, the scope of the parent method may not behave as anticipated

In my current setup, I have a parent component and a child component. The parent component contains a method within its class that needs to be triggered when the child component is clicked. This particular method is responsible for updating the store. Howe ...

Set markers at specific locations like "breadcrumbs" and generate a route using Google Maps API v3.exp

I'm developing a new iOS application for scouting out locations while on the move. I want users to be able to mark each location by simply clicking a button, which will drop a marker based on their current location. The ultimate goal is to connect all ...

Is the div empty? Maybe jQuery knows the answer

I currently have a <div id="slideshow"> element on my website. This div is fully populated in the index.php file, but empty in all other pages (since it's a Joomla module). When the div is full, everything works fine. However, when it's emp ...

Error occurs consistently with AJAX, PHP, and SQL newsfeed

Striving for Progress Currently, I am engrossed in developing a newsfeed and enhancing my proficiency in utilizing Ajax through jQuery. My ultimate aim is to create a seamless user experience where individuals do not need to refresh the page to view the l ...

Ways to access a field value in SAPUI5

As I delve into OPENUI5/SAPUI5, I'm faced with the task of accessing data for the controls I've implemented. For instance: <Label text="Amount" /> <Input id="inputAmount" value="{Amount}" /> <Text id="lblCurrency" text="USD" > ...

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

Switching the border of a div that holds a radio button upon being selected

I have a piece of code that I use to select a radio button when clicking anywhere within a div, which represents a product photo. To make it clear for the customer, I want to add a border around the selected product. Here is the initial code: <script t ...

Showing data in json format using Angular

I have designed a data table that showcases a list of individuals along with their information. However, when I click on the datatable, it keeps opening a chat box displaying the details of the last person clicked, overriding all other chat boxes. 1. Is t ...

Can I employ a PHP script as a "server" for a React application?

As I am using shared hosting without Node installed, I can't utilize Express as a server (or any other node-related features xD). The issue arises when fetching data from the Behance API in my app and encountering a CORS error. To address this probl ...

The processing indicator fails to function properly when trying to refresh a jQuery datatable

I am currently customizing the loading indicator for the datatable using a spinner called startLoadGlobal(SPINNER_DATA_TABLE_FINANCEIRO_CARREGAR_REGISTROS) in jQuery. It works correctly when I initially load the datatable, however, when I reload it, the sp ...

The Material-UI Snackbar stubbornly refuses to disappear even after setting its controlled state to false

I am currently working with a Snackbar component that relies on the redux state for control. I have implemented the onRequestClose() function in an attempt to disable the clickaway close feature. However, I have encountered an issue where setting the prop ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

Rotating through elements in timed intervals

After exploring various examples of how to show/hide divs with a JavaScript timeout, I am still unable to resolve my specific issue. I currently have six divs that I want to cycle through sequentially every 10 seconds, starting with div #one. Although my ...

Interactive search functionality using jQuery

In the panel I have, I would like to include a search input field that allows users to type in a word. As soon as a match is found, that specific word will be highlighted within the panel while the other information disappears. ...

Capturing C# log data for JavaScript interactions

Can anyone provide recommendations on how to capture JavaScript interactions in a browser using C#? I am interested in developing a web crawler that can track these interactions, allowing me to search for potentially harmful calls. ...

Ways to thwart CSRF attacks?

I am currently looking for ways to protect my API from CSRF attacks in my Express app using Node.js. Despite searching on both Google and YouTube, I have been unable to find a solution that works for me. One tutorial I watched on YouTube recommended gene ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

What is the best way to fetch multiple values using momentjs from firebase?

After fetching data from Firebase and storing it in an array, I am attempting to retrieve the posted_at values (timestamp of when something was posted) in a time format using Vuejs. However, I am facing difficulty as it only retrieves a single value instea ...

I am facing an issue with element.on('submit') not functioning properly within my AngularJS directive

I am having trouble with an ng-submit call that is supposed to trigger a submit event in my custom directive, but for some reason it's not working as expected. Take a look at this plunk to see the issue in action: <div ng-controller="MyCtrl"> ...