Guide to Binding a JSON Property (Set or Array) to an Interactive Input Form in AngularJS

My input form is structured like this:

<div>
  <div class="form-group">
    <label for="inputQuestion" class="col-sm-2 control-label">Question</label>
    <div class="col-sm-10">
      <input data-ng-model="publication.question" type="text" class="form-control" id="inputQuestion"                       placeholder="Question">
    </div>
  </div>
  <br>
  <br>
  <ul id="itemContainer">
  </ul>
</div>

<button type="submit" data-ng-click=addItem()  data-ng-click=currentid=currentid+2 class="btn btn-info">Add Item</button>

By clicking the Add Item button, items are added to the ul itemContainer using JavaScript code in the controller. Now, I want to bind these items in the itemContainer with an array attribute of "publication," let's say "publication.options." How can I make this happen?

If you think my approach is incorrect, please provide alternative methods to achieve the same outcome!

Thank you in advance for your assistance!

Answer №1

In my opinion, a practical approach would be to create an array of questions and dynamically add new questions to it.

Controller

angular.module('MyApp', [])
.controller('MainController', [ '$scope', function($scope) {

  $scope.publication = {
    question: "Is it good ?",
    options: []
  };
  $scope.addItem = function() {

    $scope.publication.options.push($scope.inputQuestion);
  }
}]);

View

<body ng-controller="MainController">
  <div>
    <div class="form-group">
      <label for="inputQuestion" class="col-sm-2 control-label">Options</label>
      <div class="col-sm-10">
        <input data-ng-model="inputQuestion" type="text" class="form-control" id="inputQuestion" placeholder="Write here...">
        <button type="submit" ng-click="addItem()" class="btn btn-info">Add Option</button>
      </div>
    </div>
    <br>
    <br>
    <h1 class="col-sm-2">Question: {{publication.question}}</h1>
    <hr/>
    <ul ng-repeat="question in publication.options">
      <li>{{question}}</li>
    </ul>
  </div>
</body>

Check out the live demo here

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

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

Exploring the power of async/await in combination with map or foreach

I am facing a challenge in retrieving multiple product prices from my database. I had initially thought of using the map or forEach methods to iterate through them and add up the prices to a variable as shown below: // Get Total exports.getTotal = (req,re ...

Using Vue.js to filter a list based on index matches

I need help with synchronizing two lists. The first list is displayed in a carousel format, and the second list contains details corresponding to each card in the carousel. I have successfully implemented logic to track the current index of the displayed c ...

What are the various ways to display time zone in a different format?

I need to display the timezone in a unique manner. I have captured the user's timezone in a variable called timeZone, which currently returns the value as Asia/Calcutta. console.log(timeZone) // "Asia/Calcutta" Is there a way to showcase the timezon ...

Creating a Distinct Interior Array Separate from the Exterior

I'm currently working on a project that involves creating a 2D array. I want the interior elements of this array to be black while the exterior elements should be white. However, my 2D array doesn't seem to be forming correctly - it looks more li ...

Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encounter ...

Using two nested for loops within a single function will not preserve an array once the loop has finished executing

When conducting a test, I encountered an issue while comparing two arrays. The test involves a filter that reads in a list of numbers and saves it to the spareArray. After clicking on a filter button (which is also the element displaying the integer list), ...

NextJs manages the logic for processing requests both before and after they are handled

NextJs stands out from other frameworks due to its lack of support for filter chains, request pre-processing, and post-processing. Many node project developers or library creators may find these features essential for executing logic before and after API c ...

The removal of the Lodash library from node modules is not occurring

In an effort to reduce bundle size, I made the decision to replace all lodash methods with core js methods in my Vuejs project. Despite attempting various npm uninstall commands such as: npm uninstall lodash npm uninstall lodash --save npm uninstall lodas ...

Trying to call the Wia class constructor without using the 'new' keyword will result in a TypeError

I'm having trouble running my code from a JSON file, as it's throwing this error message at me: TypeError: Class constructor Wia cannot be invoked without 'new'at Object. (/home/pi/wia-pi-camera/run-camera.js:3:25) 'use strict&apos ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

What is the best way to achieve a Clamp-To-Border effect on a Texture loaded onto an Image in the THREE.js?

My scene includes a plane with an image loaded onto the texture. I've found that there is no Clamp-To-Border option for textures, only Clamp-To-Edge, Repeat Wrapping, and Mirrored Wrapping. Below is an image displaying the default ClampToEdge effect. ...

What causes the body onload = javascript function to run repeatedly?

Greetings for the absolute beginners out there, just dipping your toes in AJAX. I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered. 1) It appears that the Javascript function proce ...

The Step-by-Step Guide to Deselecting an Angular Checkbox with a Button

I currently have a situation where I have three checkboxes labeled as parent 1, parent 2, and parent 3. Initially, when the page loads, parent 1 and parent 3 are checked by default, while parent 2 is unchecked. However, when I manually check parent 2 and c ...

Having trouble downloading a PDF file on a local server with React and the anchor tag element

Having trouble downloading a pdf file from my react app to my Desktop. I've reached out for help with the details How to download pdf file with React. Received an answer, but still struggling to implement it. If anyone new could provide insight, that ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

AngularJS validation for minimum character count prevents character overflow

Encountering an unusual "issue". I've set up a form with a textarea that has both a minlength and maxlength validation. In addition, there's a straightforward character count displayed: <textarea ng-trim="false" ng-model="form.text" minlengt ...

What is the best way to retrieve the title element from a loaded iframe?

Looking for a way to create a dynamic title for my iframe without manually coding it in. My goal is to extract the src of the iframe, load that object, and then retrieve the title element from it. I attempted using iframe.contentDocument but encountered ...

Tips for efficiently implementing AJAX requests for multiple forms within a single webpage

Previously, I had a form where clicking submit would hide the form and display the result on a div with classname=dig. However, after adding more forms, all the forms started submitting at the same time instead of individually. How can I fix this issue in ...