Updating a $scope variable within a loop in AngularJS

Attempting to modify a $scope variable:

Example:

$scope.variable_1
$scope.variable_2
...

Desired way of updating it:

for (i=0; i<2; i++) {    
  $scope.variable_$i = 1;
}

Wanting to access "$scope.variable_1" using the "i" index in each loop.

Any suggestions on how to achieve this? Appreciate your help.

Answer №1

JavaScript allows you to retrieve variables based on their designated names:

for (i=0; i<2; i++) {    
  $scope['variable_'+i] = 1;
}

You can learn more about this in the following resource: Dynamically access object property using variable

It is recommended to utilize arrays instead of accessing properties dynamically in this manner.

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 proper way to send a list of lists from Ajax to Flask?

Attempting to send a list of list datatype data from a template using AJAX. Here is the code: Template (JS) var mydata = [['tom', 18, 'new york'], ['jack', 16, 'london']]; var data = new FormData(); mydata.forEach( ...

Tips for hiding the overflow scrollbar on Microsoft Chrome when there is no content to scroll

Looking for a solution to hide scroll bars in Microsoft Chrome, but only when there is no content to scroll? The current div and styles always show the horizontal and vertical scroll bars, even when the height exceeds the content. <div style="backgroun ...

What is the process for implementing a custom error when compiling Sass code with node-sass?

When using node-sass to compile my sass code, I am curious about the possibilities during the compilation process. To clarify, I am interested in creating custom rules and generating specific errors under certain conditions while compiling. ...

Can an array be used as valid JSON for a REST api?

Utilizing MongoDB with Mongoskin in a web application using Node.js allows for the execution of .find() on a collection to retrieve all documents within it. The result returned is a mongodb cursor. To convert this cursor into an Array, you can utilize the ...

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...

Personalized ES6 Bootstrap module created for a toggle switch button in Vue

Utilizing the custom switch toggle in a Vue application is my current task. Check out this link for more on the custom switch toggle I found a button that suits my needs, but I am unsure how to properly integrate it into my component so it can handle the ...

What is the best way to dynamically adjust the size of a grid of divs to perfectly fit within the boundaries of a container div without surpassing them?

Currently, I am working on a project for "The Odin Project" that involves creating a web page similar to an etch-a-sketch. I have made some progress, but I am facing a challenge with dynamically resizing a grid of divs. The issue lies with the container d ...

Making a POST request across domains without relying on any third-party frameworks

Is it possible to create a cross-domain request using vanilla JavaScript without relying on frameworks like jQuery? I am looking to send a JSON to a service on a different domain and receive the response using a callback function. Can this be done solely ...

Restricting input in Angular using negative regular expressions - a new approach to input restriction directive

UPDATE: Please feel free to include additional validations that may be helpful for others within this straightforward directive. -- I am currently in the process of creating an Angular Directive that restricts the characters inputted into a text box. Whi ...

Are ES6 arrow functions not supported in IE?

When testing this code in my AngularJs application, it runs smoothly on Firefox. However, when using IE11, a syntax error is thrown due to the arrows: myApp.run((EventTitle, moment) => { EventTitle.weekView = event => \`\${moment(event.s ...

storing information between elements

Imagine I have a requirement to include a data provider element for my users, like this: <user-data-provider user-data="{{data}}"></user-data-provider> This element would send an ajax request to retrieve the logged in user's information. ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...

What is the best way to extract a value from a JSON object?

I am having trouble deleting data from both the table and database using multiple select. When I try to delete, it only removes the first row that is selected. To get the necessary ID for the WHERE condition in my SQL query, I used Firebug and found this P ...

Exploring ways to customize the input of primary key and _id in mongoose to be optional

I am looking to create a primary key in MongoDB that does not require user input, but is automatically generated. I have tried using {type: ObjectId, required: false}, but it did not work because I left the primary key empty. Is there another way to make t ...

Organize the strings by first sorting them alphabetically based on the first letter and then by length starting from the longest. Next, arrange the strings in ascending

After experimenting and seeking help on stackoverflow, I have managed to sort an array of objects based on the 'plate' key using the following function: sort(function(a, b) { return a.plate.toLowerCase() > b.plate.toLowerCase() ? a.pla ...

Client-Side Isomorphic JS: A Guide to Using HTTP Requests

Seeking advice on data population for isomorphic flux apps. (Using react, alt, iso, and node but principles are transferable) In my flux 'store' (), I need to fetch data from an api: getState() { return { data : makeHttpRequest(url) ...

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

Using v-for with nested objects

Have you been attempting to create a v-for loop on the child elements of the {song: "xxx"} object within the songs array? export const data = [ {id: "1", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : &apos ...

Can you explain the distinction between the controls and get methods used with the FormGroup object?

I have encountered an interesting issue with 2 lines of code that essentially achieve the same outcome: this.data.affiliateLinkUrl = this.bookLinkForm.controls['affiliateLinkUrl'].value; this.data.affiliateLinkUrl = this.bookLinkForm.get(' ...