Creating a Dynamic Input Field List with AngularJS: Learn how to set up a model to store an array for multiple input fields in your

Hey all you AngularJS experts, I have a thought-provoking question for you. I want to generate a dynamic list of form input fields based on a SELECT dropdown. Let's say we have different categories, each with its own unique set of specifications. To clarify, consider the following scenario:

To start, in the controller, we initialize the models.

$scope.category = {};
$scope.category.specs = [];

Then we prepare the data for the form (retrieved from the server via $http). We also set a variable to the first element in the categories array.

$scope.categories = [
  { "id": "1", "name": "mobile", specs: [ 
    { "id": "1", "label": "Operating System" }, 
    { "id": "2", "label": "Camera type" } ] },
  { "id": "2", "name": "laptop", specs: [ 
    { "id": "1", "label": "Operating System" },
    { "id": "2", "label": "Graphics Card" } ] }
};  
$scope.selectedCategory = $scope.categories[0];

In the form, there's a dropdown that loads the specific input fields when selected. The ngRepeat directive is used to create this dynamic field list based on $scope.categories.specs. (note the ???)

<select ng-model="selectedCategory" ng-options="category.name for category in categories"></select>

<div ng-repeat="spec in selectedCategory.specs">
  <label>{{spec.label}}</label>
  <input type="text" ng-model="???">
</div>

When the user clicks submit, we want to extract the selected category and its associated specifications. The post request should contain something like this (with multiple specs included):

{ "id": "1", specs [ { "id": "2", "details": "RADEON HD 8970M" } ] }

I'm unsure how to achieve this. I need to create an array for the spec model and appropriately retrieve both the ID and user-entered data...what goes in the ??? and what's next? Any help would be greatly appreciated.

Answer №1

This is my approach to handling form submission: First, I create a form and validate it using Angular. Once the form is valid, I submit it using a designated function.

  <form name="signup_form" novalidate ng-submit="signupForm()"></form>


  $scope.signupForm = function() {
var data = $scope.signup;
$http({
  method  : 'POST',
  url     : 'http://example.com/mail.php',
    data    : $.param(data), // converting data to strings
    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  
  })
.success(function(data) {

});
}

If you're interested in exploring an alternative form validation system for Angular, you may find useful in resolving any current issues with your form setup.

Answer №2

To begin in the controller, set up $scope.specDetails like this:

$scope.specDetails = {};
angular.forEach($scope.topics, function (topic, index1) {
    $scope.specDetails[topic.id] = {};
    angular.forEach(topic.details, function (detail, index2) {
        $scope.specDetails[topic.id][detail.id] = '';
    });
});

In the front end code, replace "???" with

specDetails[selectedTopic.id][detail.id]

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

Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue: Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function ...

Obtain cell values while editing in JqGrid

I am utilizing JqGrid for data entry. Initially, an empty jqgrid is displayed upon page load. When a button is clicked, an empty row is added from the client-side only. Upon clicking the empty row, it becomes editable and allows for the addition of new v ...

Display an error alert when a specific condition occurs

My page has a code snippet that triggers an error alert when loaded: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Request.QueryString["message"] == "noemployees") ...

What is the best way to access the current value and name of a textbox in real-time using

How can I retrieve the value of a textbox in JavaScript using onblur and on keyup events, while also performing real-time checking for each individual textbox using "this keyword"? Here is my JSFiddle link. Can you assist me in modifying it? ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

AngularTS - Using $apply stops the controller from initializing

Every time I launch the application, the angular {{ }} tags remain visible. Removing $scope.$apply eliminates the braces and displays the correct value. I am utilizing Angular with Typescript. Controller: module Application.Controllers { export class Te ...

Is there a way to modify the image source upon clicking a button?

I am currently working on implementing an image swap functionality on a webpage. I need the image to change when a user clicks a button, but for some reason, my logic isn't working. I am more interested in understanding why it's not working and w ...

Is it possible to showcase CSS and JavaScript code exactly as it appears when the files are saved in their respective formats, but embedded within an HTML

Recently, I've been working with notepad++ and have come across an interesting challenge. In my index.html file, I have embedded css and javascript code. Is there a way to display this code as it appears when saved in their respective files, but maint ...

Two separate projects targeting Admin and User interfaces versus a unified application featuring distinct themes for each user role

In React, there is a scenario that needs to be implemented. An admin panel with various functionalities like Auth, charts, analytics, and user management has already been pre-built. The goal now is to connect this admin panel to another website as the back ...

A Webpage that is permanently open, with no option to close it. The only option is to watch the video in

Currently, I am designing web pages for artists to showcase their work in an upcoming exhibition. The pages are ready, but now the artists are requesting that each piece be accompanied by a laptop displaying a single webpage with a video providing informat ...

Tips on integrating Next/Previous functionality for a modal Ajax popup

I have been utilizing a bPopup jQuery plugin to display ajax HTML files in a modal popup on my website. However, I am interested in enhancing this functionality to allow users to seamlessly navigate to the next slide within the modal without having to exit ...

One package in Node.js, a pair of dependencies, and a single export utilizing ES6 syntax

Currently, the library contains multiple frameworks in one npm module (which is admittedly not the best practice). However, as we work on splitting the library into separate JS framework specific repositories like React, JQuery, Angular, etc., I'm fac ...

Attempting to configure a webhook eventsub through the Twitch API by utilizing ngrok as the intermediary

After triggering a test event using the Twitch CLI, an error response was received indicating: Post "https://1562-5-182-32-19.ngrok.io/api/twitch/eventsub/": context deadline exceeded (Client.Timeout exceeded while awaiting headers). The notification even ...

Turn off hover effect for the v-checkbox component in Vuetify 2

Is there a way to prevent the darkened circle from appearing behind a v-checkbox in Vuetify 2 when hovering over it? My v-checkbox is currently enclosed within a v-tab and a v-tooltip, although I'm not sure if that has any impact. <v-tab v-for=&quo ...

What is the importance of having Actions and Reducers in Redux?

I am trying to grasp the reasoning behind the design of Redux. For instance, let's consider a scenario where I have a store with a list of todos. If the store is represented as an object like this: {1: todo1, 2: todo2, 3: todo3, ...}* And we enca ...

jqGrid - What is the best way to set up jsonreader in conjunction with Jayrock?

Seeking insights from anyone familiar with this topic. The JSON string that works well with jqGrid looks like this: {'page':'1','total':1,'records':'4','rows':[{'id':1,'title' ...

Draggable vue includes a Textarea HTML element that allows users to easily

The issue lies in implementing the draggable functionality on a textarea element. While the textarea allows text input and deletion, trying to select the text using pointer events triggers the dragging function instead, as shown in the image below: https ...

C# .NET Compile Class Name in JSON File

Currently, I am working on a C# project and I find myself in need of some guidance. At the moment, I am posting the following to my site: {Tags : 'App', Limit : '10' } And it is able to be converted to the following class: [Serializ ...

A guide on clearing the selected value in a dropdown menu with Angular.js

Can someone assist me with setting the drop-down value to blank after completing an action in Angular.js? Below is my code explanation: <div style="height:270px; overflow-x:hidden; overflow-y:scroll;" ng-show="viewOrderTable"> <div class="table-r ...

Error: Unable to retrieve data through Ajax request

$(document).ready(function(){ /* Fetching Data from TTC for Union Station */ $.getJSON("http://myttc.ca/Union_station.json?callback=?", function(data){ if (routes.length > 0) { // Display the stop details with departur ...