What is the way to activate Dynamic ng-model from a controller?

I am implementing a loop in my HTML code where each iteration dynamically creates a model. Here is an example of how the loop looks:

<tr ng-repeat="item in voucherItems">
       <td><input type="text" ng-model="this['id-' + $index]" typeahead="brand.id as brand.BRANDNAME for brand in brandList" class="input-group" /></td>                     

</tr>

The models that are created will be named as id1, id2, id3, and so on. Now, I want to utilize these dynamic models in my Angular controller.

function GetValue(indexno) {
      var model = scope."id"+indexno;
      dosomething(model);
 }

However, when trying to access the variable with the quoted part scope."id"+indexno, it does not work properly and throws an error. My question is, how can I write this portion of code within the Angular controller so that it functions like scope.id1 or scope.id2? Alternatively, how can I trigger the model dynamically?

Answer №1

I have discovered a solution using HTML.

The ng-model attribute should be set to id[$index].

In the controller, it is necessary to first declare:

scope.id={};

Then, within the GetValue method:

function GetValue(indexno) {
      var model=scope.id[indexno];
      performSomeAction(model);
 }

This approach has proven successful for me. The scope.id[indexno] behaves similarly to scope.id1 or scope.id2, etc. Special thanks to @Nora and @gianlucatursi for their assistance.

OBSERVATION: Instead of declaring scope.id={} you can also declare scope.id=[] and it will still work.

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

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

Inexperienced individual asks: 'Is it possible to accomplish this task using Dojo and Ajax?'

On my website, there is a feature that sends an initial request to a web service. Once this request is sent, the user has to wait for a specific amount of time before being able to send a second request. During this waiting period, I would like a countdo ...

Is it possible to retrieve the complete file path in a form?

My goal is to retrieve a file using an input element of type "file". This element is located within a partial view, and I need to send it to the controller or request it there using "Request.Form["inputFile"];". However, this method only provides me with t ...

Create an index.html file using webpack to utilize it with the development server

Using webpack to run my Three.js application, I have the following configuration in the webpack.config file: module.exports = { entry: `${__dirname}/src/tut15.js`, output: { path: __dirname + '/dist', filename: 'index_bundle.js&a ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

AngularJS directive that offers dynamic functionality

Currently, I am working on dynamically inserting an ng-options directive within various <select> elements throughout my application. These elements have their own unique class names and other directives, such as ng-if, among others. <div ng-app=" ...

Styling on Material UI Button disappears upon refreshing the page

I've been using the useStyles function to style my login page, and everything looks great except for one issue. After refreshing the page, all styles remain intact except for the button element, which loses its styling. Login.js: import { useEffect, ...

Check the output of the ChildProcess after executing a shell command

I am currently running the ChildProcess function within a Nextjs API route and I am struggling to retrieve the value from it. const output = exec( "curl -s -v https://test.com/index.php", (err, stdout, stderr) => { if (err) { ...

Adjusting the position of an element when the width of its parent div shifts

Struggling with the challenge of absolute and relative positioning in CSS. My GUI allows users to view folders and select how many columns they appear in, as shown in the images provided. Beneath each folder is an input field for renaming and a clear butto ...

The EJS is throwing an error because it cannot define the property "round" on an undefined object

I'm currently delving into the realm of Node.js, using the "Secrets of Ninja" book as my guide. I've come across an EJS program in the book that I copied verbatim to run, but I encountered an error despite not making any modifications to the code ...

Adjust the position of a textarea on an image using a slider

Currently, I am exploring how to creatively position a textarea on an image. The idea is to overlay the text on the image within the textarea and then use a slider to adjust the vertical position of the text as a percentage of the image height. For instanc ...

Modify a section of an HTML text's formatting

function changeEveryCharColor(id) { var part; var whole = ""; var cool1 = document.getElementById(id).innerHTML; console.log(cool1); for(var i = 0; i < cool1.length; i++) { color1 = getRandomInt(255); ...

Experiencing challenges with showcasing numerical values in the grid cells

My latest project involves creating an interactive sudoku solver. I've successfully created a grid made up of various elements to resemble an empty sudoku grid. However, my challenge lies in getting the numbers to display within the grid cells. Click ...

Improper menu alignment following a MenuItem hover event within Material-UI

When a MenuItem is hovered over, the position of the Menu container should remain unchanged. [x] The issue persists in the most recent release. However, downgrading MUI to v4.5.0 results in the expected behavior. Current Behavior ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

Unrecognized Characters in PDF JavaScript Blob

I am facing an issue with serving a PDF file from a WebApi 2 application to an AngularJS client. I use file-saver library for saving the file on the client side in TypeScript: this.$http.get(`${webUrl}api/pdf?id=${fileDto.id}`) .then((response: ng.IHt ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Passing the v-model property from a child component to a parent in VueJS

Consider a scenario where there is a Vue component structured like the following: Vue.component('child-comp',{ props:['name', 'val'], data: function(){ return { picked: '' } }, ...

Using the HTML select tag to choose an integer value with AngularJS

Looking to utilize AngularJS for the first time. One of the tasks at hand is selecting an integer value using the HTML <select> tag. <select ng-model="foo.bar"> <option ng-repeat="option in options" value="{{option}}">{{option}}</ ...

Show a message on form submission rather than redirecting

I'm working on a simple sign-up form and I want to show a success message directly on the page instead of redirecting to another page after submission. Is it better to display the message as a pop-up, an alert, or just on the page itself? <form a ...