Guide to dynamically generating Angular watchers within a loop

I'm looking to dynamically create angular watches on one or more model attributes. I attempted the following approach:

var fields = ['foo', 'bar'];
for (var i=0, n=fields.length; i<n; i++) {
    $scope.$watch('vm.model.' + fields[i], function(newValue, oldValue) {
        console.log(fields[i]); //always 'bar'
        //logic that was not giving the expected results
    });
}

Unfortunately, this code always worked with the last element of the array during each loop iteration. I've encountered similar issues with asynchronous code in the past - could that be causing this behavior here? If so, how can it be resolved?

Answer №1

The reason behind this behavior is that once a watcher is registered within the scope, the listener function is triggered asynchronously using $evalAsync to initialize the watcher -- for more details, you can refer to the official documentation and locate the first occurrence of $watch on the page.

Considering this, one way to tackle it would be by delegating to another function during each iteration of the loop, as illustrated below:

var fields = ['apple', 'banana'];
for (var i=0, n=fields.length; i<n; i++) {
    establishWatch(fields[i]);
}
function establishWatch(field) {
    $scope.$watch('vm.data.' + field, function(newValue, oldValue) {
        console.log(field); //'apple' initially, followed by 'banana'
        //code logic here to achieve the expected outcome
    });
}

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

Managing extensive text-based passages or titles within React.js

I'm curious about the most effective way to store lengthy text-based HTML elements like <p>, <h1>, <h2>, <h3> in React.js for optimal semantics. After delving into the realm of react.js documentation, I grasped that we have the ...

The client continues to request the file through the REST API

I have noticed a behavior with an audio file stored on the server that clients can request via a REST API. It seems that every time the audio is played again, a new request is sent to the server for the file. Is there a way to prevent this or cache the dat ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

Exploring the Possibilities of Wordpress Search with Multiple Dropdown Options

Is it possible to search across multiple categories? For example, I have 4 dropdown menus: 1. City 2. Area 3. Month 4. Products/Services When a user visits my site, they will see a static page with 4 dropdown lists and a "search" button. After the user ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Managing headers for localhost with Access-Control-Allow-Origin

I've run into a challenge with my React app. I'm making endpoint calls to different servers and have withCredentials set to true to include a token/cookie in the requests. The issue arises when trying to make this work seamlessly on localhost. S ...

Adjust the color of the button and update the text using AngularJS

i have been attempting repeatedly, but to no avail. Here is my button: <div ng-class="User.active? 'btn btn-danger' : 'btn btn-success' " ng-click="User.active=!User.active"> {{ User.active ? 'Desactive' : &apo ...

What could be causing the TypeError I encounter when trying to import @wordpress/element?

Encountering a similar issue as discussed in this related question. This time, I've switched to using '@wordpress/element' instead of 'react-dom/client' based on the recommendation that it also leverages React functionalities. Ho ...

Managing dynamic input texts in React JS without using name properties with a single onChange function

Dealing with multiple onChange events without a predefined name property has been challenging. Currently, one text input controls all inputs. I have come across examples with static inputs or single input functionality, but nothing specifically addressin ...

Is it possible for JavaScript/React to observe the movement of elements on the webpage?

I'm searching for a solution to detect if an element moves on the screen. Currently, I have an absolute positioned div (acting as a download overlay) that appears when a document is clicked on my website. However, I want it to disappear whenever the d ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

What is the best location to place AngularJS scope $watch functions?

I am currently facing an issue where I need changes in an AngularJS scope to trigger actions in a model. To achieve this, I utilize the $scope.$watch() method in my item controller and integrate those controllers into directives. The issue arises when an i ...

Pass the returned variable value from a request.get call to another function in NodeJS Express

I have a situation where I am calling a function that makes a request to get some JSON data and then fills in the variables from my router.get method. The issue I am facing is that the variables are getting their value inside the callFunc function, but wh ...

Using jQuery to smoothly scroll to a specific class name

I am faced with an HTML code snippet that looks like this: <div data-stored="storenow" data-save="save" class="saveIcon" data-unique="game">Save</div> My intention is to use jQuery to scroll to the game number 456 as shown below. var contain ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

Discovering the properties of a class/object in a module with Node.js

Recently I delved into the world of node.js and found myself puzzled about how to discover the attributes, such as fields or properties, of a class or object from a module like url or http. Browsing through the official documentation, I noticed that it on ...

Conundrum regarding setting up configuration for express-session middleware in Express version 4.x

Hello, I'm currently diving into node.js and still trying to grasp the concept of configurations in sessions. Below is a basic example of how sessions are used in my app: app.js var express = require('express'); var bodyParser = require(&a ...

Guide to interacting with the Li element using JavaScript in Selenium

Is there a way to click on the item inside the li element using a Selenium script with JavaScript? I've tried different methods like By.cssSelector or by css, but I keep getting an ElementClickInterceptedError: element click intercepted:Other element ...