Generating interactive form input fields using flexible ng-model functionality

I have a JSON object in my controller and I would like to dynamically generate input fields using ng-repeat.

$scope.keyValuePairs = [
    {id:""},
    {type:""},
    {brand:""},
    {category:""},
    {subCategory:""},
    {division:""}
];

And in the template:

<div class="mdl-cell mdl-cell--6-col-desktop mdl-cell--8-col-tablet" 
    ng-repeat="keyValue in keyValuePairs track by $index">
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label full-width" 
        ng-repeat="(key,value) in keyValue">
        <input type="text" id="{{key}}" class="mdl-textfield__input" ng-model="eanForm[key]" 
            name="{{key}}" ng-required="true"/>
        <label class="mdl-textfield__label" for="{{key}}">Enter {{key}}</label>
        <span class="mdl-textfield__error" ng-show="eanForm.id.$dirty && 
            eanForm.id.$invalid" for="{{key}}">{{key}} required</span>
    </div>
</div>

I am looking for a way to create dynamic ng-models so that users can add or delete form fields. How can I bind form fields to dynamic models?

Answer №1

Programming in Javascript

$scope.fields = [];
$scope.addCustomFields = function() {
    var maxIdValue= getMaxField($scope.fields, "id");
    var id = maxIdValue ? maxIdValue + 1 : 1;

    $scope.fields.push({
        id: id,
        keyName: "",
        valueData: ""
    });
};

$scope.removeSelectedField = function(index) {
    if(!index || index < 0) return;

    $scope.fields.splice(index, 1);
}

function getMaxField(arrayOfElements, propertyKey) {
    var maximumValue;
    for (var i = 0; i < arrayOfElements.length; i++) {
        if (!maximumValue || parseInt(arrayOfElements[i][propertyKey]) > parseInt(maximumValue[propertyKey])) maximumValue = arrayOfElements[
            i];
    }
    return maximumValue;
}

HTML Forms with AngularJS

<div ng-repeat="fieldElement in fields">
    Field Name: <input type="text" id="{{fieldElement.id + 'key'}}" ng-model="fieldElement.keyName" />

    Field Value: <input type="text" id="{{fieldElement.id + 'value'}}" ng-model="fieldElement.valueData" />
</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

Creating personalized tags or components by utilizing insertAdjacentHTML in Vue

With the use of insertAdjacentHTML, I am able to create HTML elements such as div and span, but it seems that I cannot generate custom tags like <myComponent> </myComponent>. I understand that insertAdjacentHTML can create HTML elements, but a ...

The field $valid status remains unchanged even after calling $setValidity(True)

I'm currently implementing my validation rules using the ui-validate directive. <input ng-model=raw.expression name="expression" type="text" required ui-validate="{serversidevalid : 'validate_serverside($val ...

Implement a dialog on top of a current web page, achieve php-ajax query result, and enhance with

My website features 'dynamic' content, where 'static' nav-buttons replace specific div contents upon clicking. While I am able to retrieve my php/ajax results in a dialog box, I am struggling with placing this dialog above my current p ...

Removing an object from the scene using three.js

Is there a way to remove an object from a three.js scene? I am trying to delete a cube when a specific key is pressed, but so far I can only clear the entire scene instead of removing just one cube. ...

Steps for Renewing Firebase Session Cookie

I am currently developing a web application utilizing Node.js/Express.js for the backend, with Firebase being used for user authentication. To manage user registration and other tasks, I rely on the Firebase Admin SDK. When a user attempts to log in, the ...

Is it necessary to include both `import 'rxjs/Rx'` and `import { Observable } from '@rxjs/Observable'` in my code?

import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Observable } from '@rxjs/Observable'; import 'rxjs/Rx'; import 'rxjs/add/observable/throw'; @Com ...

Having difficulty loading the JSON configuration file with nconf

I'm currently attempting to utilize nconf for loading a configuration json file following the example provided at: https://www.npmjs.com/package/nconf My objective is to fetch the configuration values from the json file using nconf, however, I am enc ...

Having trouble accessing the iframe element in an Angular controller through a directive

My webpage contains an iframe with a frequently changing ng-src attribute. I need to execute a function in my controller each time the iframe's src changes, but only after the iframe is fully loaded. Additionally, I require the iframe DOM element to b ...

Leveraging yield in Angular (ES6)

I have been experimenting with ES6 and attempting to use yield in conjunction with an angular request. However, I am encountering some unexpected behavior. When I write var data = yield getData();, the output is not what I had anticipated. Instead of recei ...

When displaying content within an iframe, toggle the visibility of div elements

I'm attempting to toggle the visibility of certain page elements based on whether the page is loaded in an iframe. <script>this.top.location !== this.location && (this.top.location = this.location);</script> The above code succes ...

Issues arise when attempting to use two HTTP get requests in a single AngularJS controller

Having two http GET requests in one controller, causing intermittent issues where only one of the GET requests works or sometimes none of them are shown. Any suggestions? }).controller("nextSidorAdminCtrl", function($scope,$rootScope,$http,$location,$s ...

Encountering a "POST 404 Error (not Found)" when attempting to split code into a separate

Whenever I attempt to utilize the $http POST method towards the local address "/users", a 404 error (not found) is returned. Code #1: var express = require('express'); var app = express(); var mongoose = require('mongoose'); var bodyP ...

Rejuvenate your Kendo Chart by utilizing a promise to update the DataSource

I am currently facing a challenge in my Angular application where I need to update the data source for multiple charts and then redraw them. The data source is updated through an Angular service that returns a promise. While I am able to successfully upd ...

Pass the most recent properties to the mousemove event handler

I am currently developing a click-and-drag feature, which involves: setting up a moveListener on the onMouseDown event having the moveListener trigger an action that updates certain props of the component (props.whichChange) cleaning up the mouseUp event ...

Steps for iterating through an array within an object

I currently have a JavaScript object with an array included: { id: 1, title: "Looping through arrays", tags: ["array", "forEach", "map"] } When trying to loop through the object, I am using the following ...

Experiencing difficulties with the app.post function is leading to the error message saying "Cannot

Currently, I'm facing an issue with the functionality of "app.post" while working on building a sign-up page that allows users to input their information. This is the code snippet I've put together so far: const express = require("express"); con ...

Submitting my request through Laravel API results in a successful response

I'm currently facing an issue with making a POST request from my Ionic Project in Angular to my Laravel Dingo API. Oddly enough, when I perform the POST request in POSTMAN, it successfully creates a new record. However, when attempting the same reques ...

Ways to share code across AngularJS frontend and Node.js backend

How can code be effectively shared between an AngularJS client and a Node.js server? After creating an AngularJS application, I now need to develop a RESTful server to provide data to the client. Some Angular services used on the client-side could also be ...

What could be preventing the toggle from functioning properly with the other DIVs?

Check out this fiddle link! The issue is that only the first top div is functioning properly. [http://jsfiddle.net/5Ux8L/4/][1] Here is the HTML code: <div id="top">top </div> <div id="box">box </div> <div id="top">to ...

What is the procedure for assigning an element's background-color to match its class name?

Is there a way to use jQuery to make the background color of a span element match its class? $(function() { $("span").css("background-color") }); span { display: inline-block; width: 5px; height: 5px; border: solid #0a0a0a 1px; } <script src= ...