Incorporating dynamic variables into Angular: A beginner's guide

I'm working on a form where user input determines the number of additional input boxes created. Below is the JavaScript code used for this functionality.

for(i = 1; i <= c; i++) { //c = total input count
    block = block + '<div class="row">'+
            '<div class="form-group col-lg-12">'+
                '<input id="name" ng-model="new.var'+i+'name" type="text" class="form-control">'+
                '<input id="type" ng-model="new.var'+i+'type" type="text" class="form-control">'+
            '</div>'+
            '</div>';
}
document.getElementById("vars").innerHTML = block;

The above code successfully generates dynamic ng-model variables like

new.var1name, new.var1type, new.var2name, new.var2type
, and so on.

However, I am facing difficulties accessing these variables in my controller. When trying to create them manually in the controller, an error occurs stating that 'name' cannot be found.

var var1 = [];
for(i = 1; i <= c; i++) { //c = total input count
    var item = {};
    console.log('var'+i+'name', 'var'+i+'unit');
    item['name'] = $scope.new.var+i+name;
    item['type'] = $scope.new.var+i+type;
    var1.push(item);
} 
console.log(JSON.stringify(var1));

To resolve this issue, I have modified the code as follows, but now the var1 array remains empty without any errors.

var var1 = [];
for(i = 1; i <= c; i++) {
    var item = {};
    console.log('var'+i+'name', 'var'+i+'type');
    item['name'] = $scope.new['var'+i+'name'];
    item['type'] = $scope.new['var'+i+'type'];
    var1.push(item);
}
console.log(JSON.stringify(var1));

If anyone can assist me in identifying what I am doing wrong or if this approach is feasible, it would be greatly appreciated.

Answer №1

My recommendation would be to avoid generating the html in your controller and instead write it in your view, utilizing angular's ng-repeat directive for repetition. Here is an example code snippet (not tested):

<div ng-repeat="item in c track by $index">
    <input id="name" ng-model="name[$index]" type="text" class="form-control">
    <input id="type" ng-model="type[$index]" type="text" class="form-control">
</div>

You can then access the name and type arrays from $scope within your controller. If 'c' represents the number of times to repeat, new fields will dynamically be added if that is the desired functionality.

EDITED

Within your controller:

$scope.c = 5;
$scope.getNumber = function(num) {
  return new Array(num);   
}

In your view:

<div ng-repeat="i in getNumber(c) track by $index">
    <input id="name" ng-model="name[$index]" type="text" class="form-control">
    <input id="type" ng-model="type[$index]" type="text" class="form-control">
</div>

Answer №2

try using the syntax: $scope['new.var'+i+'name']

JavaScript offers two methods for accessing object properties:

  1. If you know the name, you can use $scope.new.var1name
  2. If the name is dynamic, as in your situation, you can utilize bracket notation like this: $scope['new.var'+i+'name']

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

Is there a way to verify if a FormData file has no content?

Currently working on an AJAX form where users can choose a background color or upload a background image. The aim is to have the bgColor field ignored if a file is specified for bgImg. <label>Color: <input type="color" name="bgColor" value="#0000 ...

The combination of Stripe, Angular, and TypeScript is not compatible

Attempting to utilize Stripe.card.createToken() in order to generate a token for backend usage has proven to be challenging. Integrating this functionality with Angular and TypeScript requires careful coordination. Currently, the angular-stripe and stripe. ...

Turn off bodyparser when uploading files in Node.js

This query is quite similar to another one on Stack Overflow regarding how to disable Express BodyParser for file uploads in Node.js. The solution provided there was for Express3, but when tested with the updated Express 4, it didn't work as expected. ...

apostrophe cutting off a portion of the input field's value

I am facing an issue with a reloaded input box on a web page that is updated through an ajax call. Whenever the input contains a single quote, the rest of the value gets cut off. How can I resolve this problem? The value assigned to myVal dynamically from ...

The functionality of AC_FL_RunContent is failing after an UpdatePanel postback

In the code for the repeater item, I have a JavaScript function that calls AC_FL_RunContent to display a flash file when a link within the repeater item is clicked. The datasource I am using displays the first page of video links with five items per page, ...

How to turn off code splitting (chunks) in Vue.js and Vite.js

Is there a way to turn off chunking in Vue.js and Vite.js when building a project using Rollup.js? I attempted the following approach, but it did not work for me: export default defineConfig({ build: { rollupOptions: { output: { ...

The column headers are not being shown in Jquery datatables

This particular question is related to the thread found here. Nevertheless, my situation differs slightly. I am looking to implement the same datatables example from the aforementioned question, which can be accessed here. In that example, you must provide ...

Arranging particular components within jstree

Is it possible to use the "sort" plugin from jstree to sort specific elements only and not all nodes? Here's what I have tried so far: $('#container').jstree({ "plugins" : ["sort"] }); <script src="https://ajax.googleapis.com/ajax/l ...

Copy files using grunt, in accordance with the ant pattern, while excluding any variable directories

My task is to transfer files from the src/ folder to the dist/plugin directory. Since the version can potentially change, I would like to exclude the version number in all instances. Here is what I currently have: files[{ cwd: 'src' src ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Enhance Text Visibility following ng-view Location Adjustment within AngularJS

How can I implement text highlighting using the jquery highlight plugin after a user changes the ng-view location? The text that needs to be highlighted is on the returned page. Upon successful view change, I invoke the highlight() method: $scope.$on(&ap ...

Identifying Inactivity in Cordova Android Applications

Hey there! So, I've created a flashlight/torch app that can be found at the following link: https://github.com/Skelware/Fancy-Flashlight. This app utilizes a Cordova plugin available here: https://github.com/Skelware/Cordova-Flashlight. For now, my m ...

Can the rxjs take operator be utilized to restrict the number of observables yielded by a service?

As someone who is just starting to learn Angular, I am working on a website that needs to display a limited list of 4 cars on the homepage. To achieve this, I have created a service that fetches all the cars from the server. import { Response } from &apos ...

A guide to replicating HTML using AngularJS

I am attempting to replicate HTML content using AngularJS. While I was successful using jQuery, it caused conflicts with Angular. Therefore, I aim to achieve the same result using AngularJS. Here is the code I have written: function printContent(el){ ...

Using the Map Function in React JS to Dynamically Render Radio Buttons with Material-UI

Hey everyone, I'm looking for some assistance in replacing the old classic radio button with a new one using material-ui. I've been trying but haven't been successful so far. Any suggestions would be greatly appreciated. Thanks in advance. Y ...

Implementing import statement in three.js project causes blank page to appear

Just starting out with three.js and frontend development in general. I know this is pretty basic, but I'm facing an issue... Here's my demo setup for three.js: <!DOCTYPE html> <html> <head> <meta charset=utf-8> &l ...

Discover the best way of utilizing the `ng-class` directive for adding and removing classes!

When using the ng-class to dynamically add and remove a class by clicking a button in Angular1, I am encountering some issues. What could be causing this problem? <html lang="en" ng-app="xxx"> <head> <meta charset="UTF-8"> <ti ...

Is it possible to retrieve text from various iframes using the rangy library?

Here's a question that follows up on a problem I've been having with grabbing selected text from iframes using rangy. The code works well for the first iframe, but when I try to grab elements from multiple iframes using the same button, it doesn& ...

Performance lag with Three.js on a vertical phone screen

Recently, I transformed my codepen project into a fully functional website. However, I have encountered an issue where the performance is significantly slow when viewed on the Chrome browser of my Nexus 5X phone. Interestingly, the problem resolves itself ...

Pressing the reset button on the search box triggers a JQuery and HTML function

I am new to this, so bear with me. I've simplified my styling for easy pasting here, but the concepts still apply. I have a list of items, a working search field, and functioning filter buttons. What I want is for the filter buttons to reset to &apos ...