Utilizing ng-submit and ng-model to include a JSON object

How can I correctly insert(add) an object(nest) into a JSON using Angular?


Check out the live demo here: JSbin Link

I have a factory for Airports with a specific structure:

angApp.factory("Airports", function () {
    var Airports = {};
    Airports.detail = {
        "PDX": {
            "code": "PDX",
            "name": "Portland International Airport",
            "city": "Portland"
        },
        "STL": {
            "code": "STL",
            "name": "Lambert-St. Louis International Airport",
            "city": "St. Louis"

        },
        "MCI": {
            "code": "MCI",
            "name": "Kansas City International Airport",
            "city": "Kansas City"

        }
    };
    return Airports;
});

Connected to a Controller: How do I create a proper method to add the input to Airport.details?

.controller("AirportsCtrl", function ($scope, Airports) {
    $scope.formURL = "views/_form.html";
    $scope.currentAirport = null;
    $scope.airports = Airports;
    $scope.setAirport = function (code) {
    $scope.currentAirport = $scope.airports.detail[code];
    };

  $scope.addAirport = function() {
    $scope.airports.push();
  };


});

HTML: What should go in the ng-model to properly add an object into Airport.details Add Airport ID:

       <div class="form-group">
         <label >Code:</label><br>
        <input class="form-control" type="text" placeholder="eg. PDX">
      </div>

      <div class="form-group">
        <label>Name:</label><br>
        <input class="form-control" type="text" ng-model="" placeholder="eg. Portland Intl. Airport">
      </div>

      <div class="form-group">
        <label>City</label><br>
        <input  class="form-control"type="text" ng-model="" placeholder="eg. Portland">
      </div>
  <input class="btn btn-primary" type="submit">
    </form>

Answer №1

One major issue is that the factory is defining an object instead of an array, which is why the push method won't work as expected.

In order to send data from the form, you'll need to bind models for your form elements directly in the HTML tags:

<form ng-submit="addAirport()" ng-model="ap" >
    <h4 >Add Airport</h4>
    <div class="form-group">
        <label>ID:</label><br>
        <input class="form-control" type="text" ng-model="ap.id" placeholder="eg. PDX">
    </div>

Make sure to assign models like ap.code, ap.name, and

ap.city</code to match each form element. By binding these elements to a top-level <code>ap
object, you can save code later on.

The addAirport function should be defined as follows:

$scope.addAirport = function() {
  $scope.airports.detail[$scope.ap.id] = $scope.ap;
  delete($scope.ap);
};

This function adds the form data stored in $scope.ap to the $scope.airports.detail object, with the delete command resetting the form afterwards.

To see the updated functionality for adding airports in action, check out this jsbin: http://jsbin.com/OGipAVUF/11/edit

Answer №2

Begin by connecting all the form fields to your scope:

<div class="form-group">
     <label>Enter code:</label><br>
    <input class="form-control" ng-model="code" type="text" placeholder="e.g. PDX">
  </div>

  <div class="form-group">
    <label>Name:</label><br>
    <input class="form-control" type="text" ng-model="name" placeholder="e.g. Portland Intl. Airport">
  </div>

  <div class="form-group">
    <label>City</label><br>
    <input  class="form-control"type="text" ng-model="city" placeholder="e.g. Portland">
  </div>

Next, introduce a new hash value to the detail object:

$scope.addAirport = function() {
    $scope.airports.detail[$scope.code] = {
        code: $scope.code,
        name: $scope.name,
        city: $scope.city
    }
});

Implement some basic validation to prevent overwriting existing 'ids'.

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

Convert the entire webpage to JSON format instead of traditional HTML using Nuxt.js

My current Nuxt.js application is set up to serve HTML pages using layouts, pages, routes, and components. I'm wondering if it's possible to render a single route or page as a standard JSON response without any HTML tags - just pure JSON. Here ...

What causes the findByIDAndUpdate method to return a `null` value in Mongoose 6?

I am working with nodejs v18, Express v4, and Mongoose v6. I am attempting to update a document, but when using the line below, it returns null. const doc = await User.findByIdAndUpdate(userId, newUser, { new: true }) // doc is null The object newUser con ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

Retrieve an array from a JSON file obtained from a web request using Python

I am looking to retrieve real-time quotes from a particular page using Python 3. You can find the page here. The quotes are stored in a JSON file within an array called "JsonData". My goal is to access the value stored in LTP within this JSON file. from ...

Is it possible to add data in MongoDB without specifying a field name?

I have a couple of queries that revolve around the same concept: If I want to insert a new 'row' in MongoDB, can I do so by specifying the order of the fields? For instance, if my collection looks like items = { { name: "John", age: "28" ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

Modify payload.parameters.name according to the specified requirement in the JOLT specification

Given the input JSON below: { "payload": { "version": "1", "parameters": [ { "name": "a.b.c.d e.=f+g-h.i.j.1_2.dist [km]", "value": 0, "qualit ...

Is it common for the $scope.$digest function to be skipped in production code but necessary when running unit tests?

I understand that $scope.$digest() is not automatically called during unit testing of an AngularJs controller. Yet, I have included this code in production code within one of my controllers: $scope.$digest(function () { console.log("should be displayed ...

Using React with SortableJS to exclude specific elements from being sorted towards the end

I have a React list that looks something like this: <div id="list"> <Item data-id="1"> <Item data-id="2"> <Item data-id="3"> <Item data-id="4"& ...

What is the best way to handle a select input that may have varying options in

I'm struggling to figure out how to make each select input independent of each other when rendering them through a map function. How can I correctly implement this, especially considering that the data will be coming from a redux store in the future? ...

Manage images with Jquery and PHP/Mysql

I am currently in the process of developing a CMS and have been searching for a suitable JQuery/PHP image manager without success. Therefore, I have decided to take on the challenge of creating my own image manager from scratch. The only setback is that my ...

The HTML Style for implementing HighChart title text does not work when exporting files

I have inserted the <br/> and &nbsp; HTML tags into the HighChart titles. The style changes successfully appear in the chart view, but unfortunately, when exported as PNG or JPEG images, the text style fails to apply in the resulting images. To s ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...

Exclude a specific link from a JQuery function

Check out this unique single page site that utilizes a waypoint script for navigation and highlighting nav items - The functionality works seamlessly, however, we are facing an issue where we need to modify a link to redirect to an external website. Unfor ...

Transmit a message from the background.js script to the popup window

Currently, I am looking to integrate FCM (Firebase Cloud Messaging) into my chrome extension. After conducting thorough research, I have discovered that the most efficient way to implement FCM is by utilizing the old API chrome.gcm. So far, this method has ...

Unable to access the android static variable

In the process of creating a json from a List to store in a sqlLite database, I encountered an error in Eclipse. The error stated that the variable List must be static. However, changing this variable to static resulted in my application displaying incor ...

Make sure that the webpage does not display any content until the stylesheet has been fully loaded by

I am seeking to utilize ng-href for loading different Themes. One issue I am encountering is that the unstyled content appears before the stylesheet is applied. I have created a Plunker where I made changes to Line 8 in the last 3 Versions for comparison ...

Incorporate React JS seamlessly into your current webpage

As I delve into learning React and considering migrating existing applications to React, my goal is to incorporate a React component within an established page that already contains its own HTML and JavaScript - similar to how KnockoutJS's `applyBindi ...

Which language should I focus on mastering in order to create a script for my Epson receipt printer? (Check out the manual for reference)

Printer Model: TM-T88V User Manual: Receipt-marker Web template for the printer: (Provided by Epson) I'm completely new to computer languages and have been trying to understand how to print receipts. I've researched XML, HTML, CSS, and Jav ...

The step-by-step guide to deactivating server-side JavaScript on MongoDB using a Java application

I am working on a Java web application that interacts with a MongoDB Atlas database for CRUD operations. My goal is to disable server-side JavaScript for my Atlas instance directly from the Java web application itself. After researching, I came across th ...