Creating dynamic ng-model for input type [text] in AngularJS

Here is the current situation I'm dealing with in my code:

<form name="task_form" ng-app="myApp" ng-submit="tasksubmit()">    
 <ul class="items-list">
      <li ng-repeat="task in taskslist | orderBy:orderProp">
      <p>
        <strong>{{task.title}}</strong>
      </p>
      <input type="text" ng-model="task_input_values[task.id]" >
     </li>
    </ul>
</form>

In the taskslist array, if I have 100+ tasks, it means I will also have more than 100 identical values for ng-model on the <input type="text"> elements. Currently, I am using

ng-model="task_input_values[task.id]"
which gives me an array like {"14":"sometext here"}. However, I'm struggling to capture both the id, such as 14, and the corresponding input value like sometext here. If you have any suggestions for a better approach or logic, please share as I am new to AngularJS.

Answer №1

If you want to make changes directly to the object you are currently iterating through, you can do so easily:

<form name="task_form" ng-app="myApp" ng-submit="tasksubmit()">    
 <ul class="items-list">
      <li ng-repeat="task in taskslist | orderBy:orderProp">
      <p>
        <strong>{{task.title}}</strong>
      </p>
      <input type="text" ng-model="task.title" >
     </li>
    </ul>
</form>

Answer №2

Take a look at the live demonstration: live demo. To implement this, all you need to do is use your variable called `tasks` as an array of objects:

$scope.taskslist = [ 
     {title: "I am first text input"}, 
     {title: "I am second text input"} 
    ];

Then, simply bind to the value property of the object in the ngRepeat directive:

<form name="task_form" ng-app="myApp" ng-submit="tasksubmit()">    
     <ul class="items-list">
         <li ng-repeat="task in taskslist | orderBy:orderProp">
            <p>
               <strong>{{task.title}}</strong>
            </p>
            <input type="text" ng-model="task.title" >
         </li>
     </ul>
</form>

Since the `tasks` variable is an array, there's no need to specify the id as `tasks[$index]`, as {{tasks[$index]}} already provides you with the value of the title. For example, {{tasks[1]}} will display: {text: "I am second text input"}

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 process by which a web browser executes a ".jsx" file while in development?

As a beginner in the world of react, I have successfully been able to execute the dev and build tests. One question that has been boggling my mind is how browsers handle ".js" files. I know that when a project is build, the browser runs the &quo ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Highcharts is experiencing a duplication issue with the Y-Axis Series

This is a snippet from my code: $.get('https://dl.dropboxusercontent.com/u/75734877/data.csv', function (data) { var lines = data.split('\n'); $.each(lines, function (lineNo, line) { var items = line.split(',& ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...

Attempting to activate template rendering with Meteor session

I'm currently facing an issue with Meteor sessions and how my code is triggering the rendering of a template. At the moment, I have a session that sets its ._id to whatever is clicked. Template.sidebar.events({ /* on click of current sidecat class ch ...

Is there a way to fetch a random record from a MongoDb collection and exhibit all the fields of that haphazardly chosen document in HTML?

In my current project, I am fetching a random document from a MongoDB Collection and attempting to showcase all the fields of that document in HTML. Although I can successfully retrieve a random document, the issue arises when trying to display its fields ...

What is the best way to trigger UseEffect when new data is received in a material table?

I was facing an issue with calling a function in the material table (https://github.com/mbrn/material-table) when new data is received. I attempted to solve it using the following code. useEffect(() => { console.log(ref.current.state.data); ...

PHP Ajax login form to instantly authenticate without redirecting to a new page

After attempting to implement Ajax in my login form by following two different tutorials, I am still facing the issue of error messages redirecting to another page instead of displaying on the same page. I have tried to troubleshoot and compare my code wit ...

Notification pop-up for accepting cookies on a website

I am curious about how to insert a .js code into a button within a bootstrap alert so that when the user clicks 'accept', the alert box does not reappear. Thank you very much. Here is the code I have, but it is not working. Javascript: $(".bt ...

Images are failing to load dynamically in the Ionic application

Since updating to Ionic version 1.0.0-beta.14, I've encountered an issue where my dynamically generated images are no longer showing up. These image links are fetched using a $http.get call. I've checked the console and confirmed that the link is ...

Shared codes are compatible with both C and Javascript programming languages

Within the scope of this project, data will be retrieved from the server in either JSON or XML format. There are two separate client applications that will handle the data processing, with one being web-based and written in JavaScript, while the other is ...

An error is displayed when attempting to construct an express-react application

Currently, I am working on a project in React and ExpressJS that was previously worked on by someone else. When attempting to run the command npm run build An error is displayed in the project: https://i.stack.imgur.com/PsfpS.png How can I resolve thi ...

Tips for identifying when a tab has been reopened following closure?

There seems to be a problem with the JS state where it changes but then reverts back to its original state when the tab is closed and restored using cmd/ctrl + shift + t. Typically, data is fetched from the server via ajax using Vue's mounted() lifec ...

How can I dictate the placement of a nested Material UI select within a popper in the DOM?

Having trouble placing a select menu in a Popper. The issue is that the nested select menu wants to mount the popup as a sibling on the body rather than a child of the popper, causing the clickaway event to fire unexpectedly. Here's the code snippet f ...

Decoding strings containing spaces in AngularJS directives

I'm in the process of developing a directive for Facebook feed dialog, and I'm attempting to incorporate the item title into the directive. However, I've come across an error generated by AngularJS whenever {{current_hotel_title}} contains s ...

Instantiate an object of the ng.IQService type without using injection

Is it possible to define a local variable in the controller of type ng.IQService ( private _q: ng.IQService;) without requiring injection? My technology stack includes typescript and angular. The reason for this requirement is due to existing legacy code ...

The ng-repeat directive is specifically designed to loop through a List object, and does not support iterating over Iterable

It appears that ng-repeat only works with Lists and not other types of iterables. For example, the following code does not produce the expected result: <span ng-repeat="i in [1, 2, 3].toSet()>{{i}}</span> An exception is thrown at package:an ...

Exploring promises with loops and patience?

I created a function that accesses an API and retrieves an array containing 100 objects at once. The getPageData() function works as expected when passing an integer without the loop. However, when attempting to iterate through it, I am not getting any res ...

At what point does the cleanup function in UseEffect activate the clearInterval() function?

In the process of creating a timer for a Tenzie game, there is an onClick function that changes the state of isTimerActive from false to true when a user clicks a button. The initial value of tenzie state is also set to false, but once the user completes t ...

I'm experiencing an issue with Bootstrap 5 where the code runs fine on codeply but not on my local machine

I'm attempting to replicate the scrollspy example found on the Bootstrap website. You can see my attempt here: . Feel free to inspect the code. While the navigation links function correctly, I've noticed that according to Bootstrap's docum ...