AngularJS: monitoring changes in an array property

For the problem at hand, take a look at this link: http://plnkr.co/edit/ZphAKvZeoVtuGFSEmOKg?p=preview

Imagine you have an array structured like this:

var arr = [
 {
   'a': "123",
   'b': "654"
 },
 {
   'a': "456",
   'b': "321"
 }
];

arr.foo = 'bar';

$watch will trigger when there are changes made to the objects within (for example arr[0].a = 'hoopidoo'), yet it won't detect changes to foo (like arr.foo = 'deedlilaa', or via ng-model). This could be due to a limitation in JavaScript. When iterating through the array, only the objects are returned, and therefore foo cannot be enumerated.

View the plunker for further clarification. The watch event does not get triggered regardless of input modifications or controller actions.

Answer №1

To properly observe the properties of an Array object (as opposed to objects with specific keys), you must use the $watch function:

$scope.$watch('arr.param', function(newVal, oldVal) {
   // Add your code here
}
arr.param = 'foobar'

Alternatively, if you are not concerned about mixing numeric and associative array keys, you can simply update Line 37 of your plunker like so:

$scope.arr['param'] = "abc";

Answer №2

Utilizing:

$scope.$watchCollection

You can use $watchCollection to monitor changes in variables within the scope and update elements like buttons or any necessary components.

$scope.$watchCollection(function () {
    if ($scope.myForm)
        return $scope.myForm;
}, function () {
   if ($scope.myForm)
   if (($scope.myForm.$invalid == true))
          $scope.formValidityChange(true);
    else
        $scope.formValidityChange(false);
}, true);

This allows you to track all changing variables inside a form and make updates in the controller accordingly. Comparing the two objects for changes may present a bit more complexity, but it is achievable.

Answer №3

When using Javascript arrays, it's important to note that they do not support "string indexes". If you try to access an element using a string index like arr.foo, the type of the array arr will be converted from an Array to an Object.

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

Checking the security status of a PDF file in the web browser to determine if it

Within my platform, individuals have the ability to upload PDF files for others to access at a later time. In order to accommodate this functionality, I require that these PDFs are not secured or encrypted, and can be easily viewed by any user. To ensure ...

Error encountered in Express middleware: Attempting to write private member #nextId to an object that was not declared in its class

Currently, I am in the process of developing a custom logger for my express JS application and encountering an issue. The error message TypeError: Cannot write private member #nextId to an object whose class did not declare it is appearing within my middle ...

What could be causing the code to produce 4 elements instead of the expected 2?

I'm trying to understand why the code above is creating four new paragraphs instead of just two. Can someone please explain what exactly happens in the $("p").before($("p").clone()); part? <!DOCTYPE html> <html> <head> <script ...

Discover the smallest value in a 2D array of strings using Java

For my assignment, I am working with a 2D array of strings that contains student names, courses/subjects, and the marks each student received in each course. The goal is to identify the lowest mark in each course. For example, in Math: Student A scored 78, ...

Techniques for manipulating multiple circles with JavaScript

After creating a series of circles with d3, I successfully implemented the functionality to drag individual circles and track their positions. var width= 800; var height=600; svg= d3.select("body").select(".div1").append("svg") ...

Upon opening index.html in the browser, the jQuery code fails to execute, as no errors are displayed in the console

I am struggling to make a simple toggleClass() function work in jQuery and I can't seem to figure out why. This is just a beginner exercise for me with jQuery. The code works perfectly when I test it as a snippet or manually in the console, but when I ...

What issues could potentially arise from utilizing the MIME type application/json?

I'm currently developing a web service that needs to return JSON data. After doing some research, I found recommendations to use application/json. However, I am concerned about potential issues this may cause. Will older browsers like IE6+, Firefox, ...

By default, the sidebar is open on desktop devices while closed on mobile devices

I am struggling to figure out how to set my sidebar/navigation content, using Bootstrap, to be expanded by default on desktop and closed by default on mobile with the icon only showing on mobile devices. Despite multiple attempts, I cannot seem to make thi ...

Utilizing jQuery/Ajax to send an ID parameter to a PHP script

This code is where the user interacts. <html> <head> <title></title> <script src="jquery-1.9.1.js"></script> <script src="jquery.form.js"></script> </head> <body> <?php include 'con ...

What is the method to retrieve the index or row number using the map function in Google Sheets?

Currently, I am attempting to retrieve the row number where the row meets certain criteria. However, I seem to be encountering an issue: Instead of getting the desired result, I am obtaining an array like this: [,,2] Although I have attempted using filter ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

Manipulate the visibility of div sections depending on the selected price and category checkboxes using JavaScript

I have a unique div setup where I'm defining data attributes to display a product list. Each div contains data attributes for category (data-category) and price (data-price). I want to be able to show or hide specific divs based on selections made usi ...

There seems to be a problem with the formatting in "{{start_time | date:'HH:mm'}}". I am receiving a warning message and the formatting is not applying correctly

Encountering a warning message indicating that the format is not being displayed correctly in the input field. The value "{{start_time | date:'HH:mm'}}" does not match the required format. It should be in the form of "HH:mm", "HH:mm:ss", or "H ...

"Enhance your website with a backspace button using jquery - here's

Recently, I delved into the world of jQuery and decided to test my skills by creating a jQuery calculator. Everything worked perfectly except for the backspace button. This is what I tried: if (value === backspace) { $(input).val($(input).val().substring ...

Generate a 2D array resembling a grid

I have limited experience with Java and am facing a project with tight deadlines. I need assistance with the following class: public static void getAllDataDB1() // Retrieving data from the "bank1" database { try { MetaData1 ...

Retrieve the value from a promise using the $q.all function

I am attempting to retrieve the returned values of promises using the $q.all() method. This is what I have implemented so far. var promise1 = function(time){ var defered = $q.defer(); var promise = defered.promise; def ...

Passport verification is successful during the login process, however, it encounters issues during registration

I am currently learning about passport.js and session management, and I'm in the process of implementing a local login feature on my website. Here is what I am attempting to achieve: Secret page: Authenticated users can access the secret page, while ...

The process of integrating Tailwind elements into NextJs version 13

Can anyone help me integrate Tailwind elements into my NextJs project using JavaScript instead of TypeScript? I tried following the documentation, but the navbar component's expand button doesn't work. It seems like all components are having some ...

Establish a single route for executing two different statements in MSSQL: one for updating and the other for inserting data into the MS-SQL

I have a Node application where I currently insert data into one table, but now I also need to insert it into another table. The issue is that I am unsure how to execute a second promise for this task. var query = "first SQL query..."; var query2 = "new ...

Guide to attaching data to an AJAX request

I'm new to ajax and recently encountered an issue while working on a project where I needed to send a query from an HTML form. However, I've been unable to send any data for some reason. I tried sending FormData through the xmlhttprequest.send() ...