Bidirectional data binding of textarea in AngularJS

To gather user responses to a list of questions, I created a form.

Here is the HTML form:

<div class="list" ng-repeat="question in questions.data.Question" > 
      <div class="item item-divider">
         {{question.text}}
  </div>
    <label class="item item-input" ng-if="question.type =='comment'">
      <textarea placeholder="Comments"></textarea>
   </label>
 </div>

Now, my JSON string looks like this:

{
    "sucess": true,
    "message": "record(s) fetched sucessfully",
    "data": {
        "Question": [
            {
                "id": "4",
                "text": "how was it?",
                "type": "comment"
            },
            {
                "id": "6",
                "text": "how was it?",
                "type": "comment"
            }
        ]
    }
 }

When the user submits the form, I need to capture the comments they provided for each question.

Answer №1

While I am not an expert in Angular, it seems that adding ng-model to the textarea element is necessary.

<div class="list" ng-repeat="question in questions.data.Question" > 
      <div class="item item-divider">
          {{question.text}}
      </div>
      <label class="item item-input" ng-if="question.type =='comment'">
          <textarea placeholder="Comments" ng-model="question.comments"></textarea>
      </label>
 </div>

Additionally, you should include a 'comments' field for each question of type comment. Here's an example:

        {
            "id": "6",
            "text": "how was it?",
            "type": "comment",
            "comments": ""
        }

Please note that adding a "comments" field may or may not be required depending on any potential 'force add field' flag specific to angularjs that I may be unaware of.

Answer №2

To make the textarea work, you need to bind ng-model to it, even if the "answer" variable is not initially present in your json data. I included a button for demonstration purposes. For a complete example, visit JSFIDDLE

<div id="qApp" ng-controller="qAppCntrl">
 <div class="list" ng-repeat="question in questions.data.Question track by $index" > 
  <div class="item item-divider">
     {{question.text}}
  </div>
  <label class="item item-input" ng-if="question.type =='comment'">
    <textarea placeholder="Comments" ng-model="question.answer"></textarea>
  </label>
 </div>
 <button ng-click="submit()">Post</button>
</div>

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

Tips for incorporating cookies into your Electron and AngularJS application

I am working with electron and angularjs using electangular, which provides access to all electron methods within angularjs. Currently, I am trying to set a cookie in my application's controller: var BrowserWindow = electron.BrowserWindow; va ...

Using JavaScript to connect with the OFX Server

I'm currently working on a project that involves calling the OFX server from my Javascript file. I've been using the jQuery ajax method to make this web service call. However, when I try to call the web service, I keep encountering the following ...

What could be causing my chessboard to not wrap around properly with flexbox?

I have been working on creating an 8x8 chessboard by following this example: https://codepen.io/sammyslamma/pen/gJeOwY .flex-container { display: flex; flex-flow: row; flex-wrap: wrap; ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

Checking for valid patterns in HTML strings

After writing a code to pass strings into an API, I realized that these strings must adhere to a specific pattern. Once the pattern is satisfied, clicking a button calls an API to store the strings. Passing string to database <link rel="stylesheet" ty ...

Keeping returning visitors engaged without triggering negative reactions from bots: What's the best approach?

Looking to provide new visitors with an introduction on certain pages of website.com without being repetitive if they have already seen it. For example, if a user lands on website.com/cool-article, the introduction is displayed at the top. However, when t ...

How to adjust the width of nested divs in Nuxt.js/Vue.js to align with a specific container in the stack

Is there a way to handle varying image widths in Nuxt without compromising the layout? I have an image component that needs to adjust for different screen sizes, and I want the title and description to always match the width of the image. Here's what ...

Save the discovered word in an array as a variable

let variable = process.env.a for(let item of variable){ if(message.content.toLowerCase().includes(item)){ var vsFound = //The Word Found In A Discord Message message.reply("Said " + "'" + vsFound + "'&q ...

creating a promise within a .then() function to pass along for future use in a different function

Currently, I am utilizing a native script firebase plugin that requires the following function: getCompanyValue() { var value; firebase.getValue('/companies') .then(result => { console.log(JSON.stringify(result ...

Struggling with using connect() while learning react/redux

While on my quest to self-teach react/redux, I encountered a challenge with the connect function. My goal is to develop a chess game where a piece moves to the selected square upon clicking. Currently, I only have a knight piece and all I need is for it to ...

When data is changed, the cursor automatically moves to the end of the input field

Seems like this issue is only occurring in Chrome. It functions correctly in Firefox and Safari. Oddly enough, when I try to edit the value in the input field, the cursor automatically moves to the end of the text. There have been similar problems reported ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

Issues with Django Site Search Functionality

Currently working on a Django project, I have encountered an issue with the search bar on my localhost site. Despite adding the search bar, it fails to return any results when provided input. Upon inspecting the page source, I discovered some unfamiliar li ...

Error: The module 'semver' could not be located during the npm installation process

Having trouble with npm install in the NodeJS command prompt. When I run npm install, I encounter the following errors: module.js:339 throw err; ^ Error: Cannot find module 'semver' at Function.Module._resolveFilename (module.js:337: ...

Best practices for customizing v-calender in vue.js

I'm struggling with styling my calendar using the v-calendar Vue plugin. I want to customize the background of the calendar, but my code doesn't seem to be working. Can someone please help me out? Thank you in advance. HTML <v-calendar ...

Phonegap app developer encounters issue with sending ajax requests

Recently, I encountered an issue with Ajax in my Phonegap development. Previously, it worked perfectly but now when I call the Ajax function, nothing happens. Here are the steps I have taken to troubleshoot: 1) I edited the config.xml file and added the f ...

The functionality of my "add to cart" button and the increment/decrement buttons are currently malfunction

I am currently facing an issue with my Add to Cart button. Although there are no errors, the button is not displaying any output when clicked. I have also tested it with the alert function and noticed that the increment and decrement buttons for quantity ...

``Troubleshooting: Ineffectiveness of updating session variables

<?php session_start(); include 'cardclass.php'; $cards = new deck(); $cards = unserialize($_SESSION['cards']); $cards->drawCard(); $cards->pushBack(); $_SESSION['cards'] = serialize($car ...

The jqGrid is not showing the AJAX JSON data as expected

Currently, I am exploring jqgrid and trying to figure out how to display data in another jqgrid when clicking on a specific colmodel. The retrieved data from the server goes through a function and reaches the grid, but no information is displayed without a ...