Enhance your JSON formatting with dynamic fields

I am currently working on creating a form with dynamic fields in order to generate a JSON format for posting. The challenge lies in the structure of the JSON, particularly with the "envname" and "value" fields which need to be dynamically added based on user input.

My main hurdle is integrating these dynamic fields with regular fields within the same scope. I have attempted various methods but cannot seem to get everything to work together seamlessly.

If you would like to take a look at my progress so far, please visit http://jsfiddle.net/q9dcn7wj/3/. Currently, the cpu and ram fields are being ignored when I make changes to the code.

Any suggestions or guidance on how to properly submit the entire form as JSON would be greatly appreciated.

Answer №1

You seem to be treating your inputs model as both an array and an object.

One suggestion is to create a variables property on your input model and then use push/splice on that.

I've made some updates to your JSFiddle, with the relevant code snippet below:

JavaScript:

var app = angular.module('myApp', []);

app.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.inputs = { variable: [] };

$scope.addInput = function(){
    $scope.inputs.variable.push({name:'', value:''});
}

$scope.removeInput = function(index){
    $scope.inputs.variable.splice(index,1);
}
}]);

HTML:

<div ng-app="myApp" ng-controller="MyCtrl">

        <input type="text" ng-model="inputs.cpu" />cpu<br />
        <input type="text" ng-model="inputs.ram" />ram

    <div ng-repeat="input in inputs.variable">
        <input type="text" ng-model="input.name" />
        <input type="text" ng-model="input.value" />
        <button ng-click="removeInput($index)">Remove</button>
    </div>
    <button ng-click="addInput()">add input</button>
    <br />
<strong><label for="userDebugText">JSON:</label></strong>
<textarea id="userDebugText">{{inputs|json}}</textarea>
</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

Store the encoded data in a variable

After looking at some examples, I attempted to create my own solution but encountered an issue with the Promise being stuck in a "pending" state. My goal is to store base 64 data into a variable named base64. Can anyone offer guidance on what's wrong ...

Default output to the browser in JSON using Django Rest Framework

Is there a way to make the URL return JSON by default without having to specify ?format=JSON? I am using djangorestframework ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Using BackboneJS to fetch JSON data and render it on a view

I am attempting to utilize backbonejs to retrieve JSON data from the server and display it in a view. Unfortunately, my current implementation is not functioning as expected. Below is the backbonejs code snippet: $(function () { var Service = Backbone.M ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

Tips on finding the right parent object by utilizing the information stored in the nested array

I have a collection of objects structured as follows: var items = [ { itemId: 0, itemQuantity: 10, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "Black" } ] }, { itemId: 1, itemQuantity: ...

Rhino's env.js causes the anchor element's pathname to be undefined

Encountered an issue that appears to be related to how anchor tags are implemented in Rhino. Despite using env.js, there might be a configuration error causing the problem. The issue arises when writing unit tests for code designed for an angularjs applic ...

Troubleshooting: Difficulty Reading .val() on Elements Selected by Class in jQuery.fn.init(9)

I am facing an issue while trying to retrieve all elements with a specific class name using the code below: productPrices = $('.product-price'); Instead of getting individual values, I am getting the following output: jQuery.fn.init(9) [div. ...

Can WS Websocket in Swift send and receive JSON objects?

An unhandled exception 'NSInvalidArgumentException' is causing the app to terminate, with the reason being 'Invalid type in JSON write (_NSInlineData)' Define the data variable as the type of data being used Let dictionary : NSDictiona ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Dynamically loading various compositions of EDGE

I'm currently working on developing a testing system for edge-animate compositions. The goal is to be able to load different compositions and verify that they are displaying correctly, as well as make changes to their customizable fields. I attempted ...

Eliminating repeated entries in MongoDB

Hey guys, I've been struggling for days trying to eliminate all the duplicates from my database. I attempted a solution I came across on this Link, but encountered an error message stating that forEach is not a function. I'm puzzled as to why it ...

Creating custom functions within views using Sencha Touch 2

I'm having trouble creating my own function in Sencha Touch 2 and I keep receiving an error: Uncaught ReferenceError: function22 is not defined The issue seems to be coming from my Position.js file located in the View directory. Ext.define(' ...

Preventing typing by detecting keypresses in a text input

I'm trying to set up a text input field so that it triggers a function when the Enter key is pressed. I currently have an if condition to check for the Enter key press, but this prevents users from typing in the input box. What should I include in the ...

Having trouble with a JQuery selector not functioning properly when trying to select a class in the HTML that contains a

Looking for help with a JQuery selector to target the title of a YouTube video. Here's the HTML snippet: <div class="ytp-title-text"> <a class="ytp-title-link yt-uix-sessionlink" tabindex="13" target="_blank" ...

Optimal method for Python to engage with MySQL databases

As a beginner in programming, I am currently teaching myself the correct ways of coding. My current project involves writing a script in Python that will receive 1-3 values every second and save them to a MySQL database. Eventually, I plan on creating a we ...

Managing Pop-Ups when browsing on Internet Explorer

I've been working on an Excel VBA macro that automates several tasks on the Medicare website. The macro opens IE, logs in, compares claims, and alerts me to any differences found. However, I've encountered a problem during the log-in step, specif ...

Encoding the class hierarchy using Newtonsoft Json serialization

I'm currently working on serializing a class hierarchy in C# using Newtonsoft Json. Here is an example of my class structure: public abstract class Foo { public string PropertyOne{get;set;} } public class Bar : Foo { public string Property ...

Is it possible to execute this html-minifier through the terminal on Ubuntu?

I am encountering an issue while attempting to use this HTML minifier tool on Ubuntu via the command line. Every time I try to execute it, an error pops up. NodeJS and NPM installations go smoothly: root$ apt-get install -y nodejs npm Reading package lis ...

Reverse the color of H1 text within a vertical div

Is it feasible to reverse the coloring of a segment within an h1 element using a div, horizontally? Refer to the illustration shown in the image below. https://i.sstatic.net/QAKwD.jpg ...