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

Is there a way to upload multiple files using expressjs?

I'm looking for a way to efficiently send multiple files, including an entire directory, so that I can access them in another JavaScript file called from an HTML file. const app = require("express")(); const http = require("http"). ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

Learn the best way to send query parameters through the Next.js navigation router and take advantage of

Currently, I am implementing import { useHistory } from 'react-router-dom' const history = useHistory() ... history.push('/foo?bar=10') However, only the 'foo' part is being pushed into the url. What is the correct way to pas ...

What is the best way to access the methods in the "parent" class?

I am facing a situation where I have an object with fieldsCreators that hold creator methods for each field. The dilemma is how to call the creator method inside fieldsCreators as shown below: var obj={ creator:function(ch) { .... .. ...

The Material UI Icon is missing from the location '@mui/icons-material/Send.js'

I am currently utilizing the Material UI library and attempting to import SendIcon through this import statement: import { SendIcon } from "@mui/icons-material/Send.js"; Due to including "type" : "module" in my package.json f ...

Transmitting the User's Geographic Location and IP Address Securely in a Hidden Input Field

I'm looking to enhance my HTML form by retrieving the user's IP address and country when they submit the form. How can I achieve this in a way that hides the information from the user? Are there any specific elements or code additions I need to ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...

Tips for ensuring that the horizontal scroll bar remains consistently positioned at the bottom of the screen

There are two div sections on a page, with one positioned on the left and the other on the right. The div on the right contains multiple dynamically generated tags which necessitate a horizontal scroll bar (overflow:auto). This causes the div's height ...

Apply a class to each consecutive element following the current one until reaching a child element with a

My goal is to apply a "bg-info" class using jQuery to all rows (tr) that come after odd rows with a child element of "test". The "bg-info" class should be removed when a row with a child element of "test" is encountered, and then re-applied when the next o ...

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

A guide to managing Ajax in functional components in React without using classes

Currently, I am striving to develop all my components as pure functions. However, I have encountered an issue. The component I am working on resembles the structure below. The problem arises when the result of an ajax request triggers a rerender, leading ...

Flag form field as invalid in AngularJS

Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message? Here's the setup of my app: I have a model 'client' with a controller Accounts.controller(&ap ...

Having trouble grasping the purpose of app.use('/') in the Express framework

Below is the code snippet I am currently working with: // Initializing express, body-parser, mongodb, http, and cors var app = express(); app.use(cors()); app.use(express.urlencoded()); // Parse incoming JSON data from API clients app.use(express.json()); ...

What is preventing my counter from functioning when I click on the canvas?

I am attempting to increment the count every time a bouncing ball in the browser is clicked using this.setState({count: this.state.count + 1});. I thought my code was correct since I have done similar tasks before without using canvas, but it's not fu ...

Issue with Jquery: Checkbox fails to get checked in Internet Explorer 7

Having trouble with checking a checkbox, I've attempted the following steps: $('#someId').attr('checked','checked'); $('#someId').attr('checked', true); Both of these methods are effective for I ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

The AJAX request was successful, however, the PHP script did not return any

When using an Ajax success function to alert data in JavaScript, there may be occasions where the PHP side shows that the GET array is empty. <script type="text/javascript"> var myArray={ name:"amr", age:22 } myArray =JSON.stringify(myA ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

Mongoose/JS - Bypassing all then blocks and breaking out of the code

If I need to check if a certain ID exists and exit the process if an error is encountered right from the beginning, is there a more concise way to do it rather than using an if-else block? For example: Question.find({_id: req.headers['questionid&ap ...

Learn how to gradually make text disappear and reappear using JavaScript or jQuery

I am a beginner in JavaScript and jQuery, and I am trying to achieve a text fade-out effect. Once the text has completely faded out, I want it to return with the same fade-in effect. I have been exploring if statements and fadeIn effects, but I am strugg ...