The combination of $watchCollection and multiple expressions is not effective

Having two arrays with boolean values, I attempted to use the $watchCollection function to trigger a message when changes occur in either array. However, it seems that the function is not working as expected.

To diagnose the issue, please refer to this example

Controller

  $scope.arrayCategoryA = [];
  $scope.arrayCategoryB = [];

  $scope.$watchCollection(['arrayCategoryA', 'arrayCategoryB'], function(newVal, oldVal, scope){
    console.log("something changed");
  }, true);

  $http.get("categoryA.json").success(function(data) {
     $scope.categoryA = data;
     for (var i = 0; i < $scope.categoryA.length; i++) 
     $scope.arrayCategoryA[i] = true;
  });

  $http.get("categoryB.json").success(function(data) {
     $scope.categoryB = data;
     for (var j = 0; j < $scope.categoryB.length; j++) 
     $scope.arrayCategoryB[j] = true;
  });

Answer №1

Observing and reacting to changes in a specific value has been possible with AngularJS through the Scope.$watch() function. However, starting from AngularJS 1.1.4, the Scope.$watchCollection() function was introduced to monitor changes within a collection (either an Array or Object).

It's important to note that $watchCollection is designed to work for only one array or object at a time, requiring adjustments to code for single watch implementation.

$scope.$watchCollection('arrayCategoryA', function(newVal, oldVal){
    console.log("something changed 1");
}, true);
$scope.$watchCollection('arrayCategoryB', function(newVal, oldVal){
    console.log("something changed 2");
}, 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

What is the reason skip does not function properly at the start of the aggregation pipeline, yet performs as expected at the conclusion of it?

Initially, the skip stage in this MongoDB database aggregation framework pipeline isn't functioning as expected: [ { $skip: (!offset)? 0 :(offset-1)*limit }, { $match: (query)? query : {} } , { $lookup: ..., ...

bcryptjs function can perform create operation properly but encounters issues with insertMany operation

bcryptjs package version: "bcryptjs": "^2.4.3" Mongoose library version: "mongoose": "^6.0.12" Currently, I am working on encrypting user passwords during user creation or password updates. Everything works smoothl ...

Add unique styles to a jQuery-included HTML document

I'm attempting to use jQuery to load an HTML page into the main body of another page. Specifically, I have a div called sidebar_menu positioned in the middle of the page, and I am loading content at the bottom using jQuery. $("#sidebar_menu").load(" ...

Guide to assigning values to Input<input> and Select <select> elements using Javascript

I am looking to automatically set values in an input or select tag based on certain conditions defined in the JavaScript code below. However, I am facing an issue where the data does not get reflected in the database upon submitting. Any suggestions or cod ...

Experiencing problems with the Datepicker and cloning functionality in JQuery?

This is the section of code responsible for cloning in JavaScript. $(document).on("click", ".add_income", function () { $('.incomes:last').clone(true).insertAfter('.incomes:last'); $(".incomes:last").find(".income_date_containe ...

I'm experiencing difficulties in installing dependencies for my project through npm, as it keeps showing an error

Recently, I decided to delve into the world of HTML5 and javascript games by running a browser game from Github. The game that caught my eye is called BrowserQuest, and you can find it on Github. A hiccup arose while using npm debug: 237 error 404 Not ...

Determine the variance between two strings using Jquery

Hello and thank you in advance for your help. I'm facing a basic query here - I have two variables: var x = 'abc'; var y = 'ac'; I am looking to compare the two variables and find the dissimilarity between them, which should be: ...

Ensure accurate interpretation of CSS3 transform percentages on Android devices

tl;dr? Looking for a way to enable GPU acceleration on Android Chrome & default browser for the mechanism shown in the link below. UPDATE 2 (2014-01-13 13:25:30Z): As per bref.it's comment, the issue was resolved with Android 4.4 KitKat but my previo ...

Evaluating the functionality of gRPC features

I've been tasked with testing gRPC client call functions using Jest. Below is an example of a typical node.js function: client.authenticate(request, meta, (error, response) => { if (!error) { console.log('REPLY FROM SERVER: ', r ...

Changing the color gradient of a range column chart in ApexCharts

Currently, I am working on a project where I am trying to incorporate a waterfall chart using ApexCharts. Unfortunately, the Waterfall chart is not readily available with ApexCharts, so I am experimenting with modifying the range column chart into a Waterf ...

Javascript function failing to execute upon page load

I don't have much experience with JavaScript, but I found the following code in a .htm file. The function doesn't seem to be triggering when it should; It is supposed to activate when the page is directly opened i.e www.site.com/12345.htm This ...

AngularJS encountered an error while attempting to create a module with obfuscated code, resulting in a $injector:

Attempting to obfuscate my angularjs application using mangling is resulting in an error. I have been advised to use ngmin to address this issue. Following this advice, I have successfully used ngmin to properly encapsulate my controller code within an arr ...

The function signature '(priority1: number, priority2: number) => number' cannot be assigned to the parameter type '(a: unknown, b: unknown) => number'

I encountered the following type error (TypeScript - 3.7.5). Error TS2345: Argument of type '(priority1: number, priority2: number) => number' is not assignable to parameter of type '(a: unknown, b: unknown) => number'. Typ ...

Troubleshooting a JQuery GET request failure

I'm attempting to send a GET request once the user inputs a value and use that input as a parameter, but nothing seems to be happening. The alert outside the get function is working fine. Here's my code: $(document).ready(function(){ $( "input[ ...

Angular: the uncertain numeral formatter

Looking to customize the behavior of the Angular number filter? Want it to leave the input unchanged if it's not a number? <my-tag input-value="{{foo() | number: 2}}"></my-tag> If foo() outputs 1.2345, display 1.23, but if it's "abc ...

How to Retrieve a Date using Month, Week, and Day Numbers in JavaScript

Could anyone assist me in extracting the date (yyyy-MM-dd) from the following parameters: year : 2021 month : 2 (February) week : 1 (1st week of February) day : 1 (Monday) Any suggestions or ideas would be greatly appreciated! Thank you! :) ...

Prevent Copying, Defining, or Sharing in iOS Safari Selections

A Cordova App has been developed using Angular JS, with the Apple webview copy/share/define menu disabled from the view code in Xcode to prevent it from popping up. The Angular JS code is also available on a website accessible by desktops, where the Copy/ ...

When utilizing prompt() in React, the issue arises where the page continues to refresh

Being a newcomer to React, I decided to create a very basic project that utilizes the "prompt()" function in JavaScript to gather a user's age and then displays it using React. By clicking on the "Change Age" button, you can modify the displayed age b ...

Using Vue to cycle through an array of objects, and emphasize the chosen item by clicking on it

I have to display an array of objects in the DOM by using map method. Each item has a @click event listener where I want to highlight it with a CSS class 'hover'. The desired functionality is to mimic a menu system where only the clicked item sho ...

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...