Creating a JSON object in AngularJS is a simple and straightforward process

Is it a good practice to create a JSON object in AngularJS this way? Or is there a better solution to achieve the desired format?

Edit question:

I am trying to create an object in JSON format as shown below. I have written the code but facing difficulty in adding an object to the orders array. How can I add a new object to the orders array?

  [
{
  "date":'2015-30-7',
 "baskets": [
   {

     "orders": [
      {
        "id": "12"
      }
     ],
     "customer": {
      "phone": "555555"
     },
     "discount": "8"
    }
  ]
 }
]

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


app.controller('myController', function($scope, $http) {
  $scope.typistData = [];
    $scope.typistData.push({
      baskets: [{
        orders:[]
      }]
    });
    
  $scope.addBasket = function() {
    $scope.typistData.push({
     baskets: [{
        orders:[] 
      }]
    });
    
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>

        <input type="text" ng-model="data.name">
        <hr>
  <div ng-repeat="data in typistData" ng-if="typistData">
    <form  novalidate ng-submit="submitOffices()">

      <div>
        <ng-form  ng-repeat="basket in data.baskets">
          <div>
            <input type="text" ng-model="basket.customer.phone">
            <br>
            <input type="text" ng-model="basket.discount">
             <input type="text" ng-model="basket.orders[0].id">
                <input type="button" value="addOrder">
          </div>
          <hr>
        </ng-form>
      </div> 
    </form>
  </div> 
   <button ng-click="addBasket()">Add Basket</button>
  <div>
    <pre>{{ typistData | json }}</pre>
  </div>
 
</div>

Answer №1

It seems like you are looking to add a basket to the baskets of any typist and also add an order to the orders of one of the typist's baskets. To achieve this, you can pass the right objects for addBasket and addOrder inside ng-repeat with ng-click to work with references. Here is a possible implementation:

View section :

<div ng-repeat="data in typistData" ng-if="typistData">
  <form novalidate ng-submit="submitOffices()">

    <div>
      <ng-form ng-repeat="basket in data.baskets">
        <div>
          <input type="text" ng-model="basket.customer.phone">
          <br>
          <input type="text" ng-model="basket.discount">
          <input type="text" ng-model="basket.orders[0].id">
          <button ng-click="addOrder(basket)">Add Order</button>
        </div>
        <hr>
      </ng-form>
      <button ng-click="addBasket(data)">Add Basket</button>
    </div> 

  </form>
</div> 

Controller section :

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

app.controller('myController', function($scope, $http) {
  $scope.typistData = [];
  $scope.typistData.push({
    baskets: [{
      orders:[]
    }]
  });

  $scope.addBasket = function(typist) {
    typist.baskets.push({
      orders:[] 
    });
  };

  $scope.addOrder = function(typistBasket) {
    typistBasket.orders.push({
      // Add order details 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

Having trouble retrieving IDs in a Many-to-Many relationship with Django 2.0.2

I'm currently working on a web application using Django 2.0.2 with Full Calendar and Bitnami Stack integration. I've encountered some challenges with understanding the Many-to-Many relationship in Django. My goal is to match all relevant resource ...

Removing a Child Object from a JSON Object in AngularJS

Encountering an error while attempting to remove a Child object Error Message: TypeError: ctrl.otsact.tests.splice is not a function HTML : <tr ng-repeat="act in ctrl.otsact.tests" ng-if="ctrl.editToggle"> <td><span ng-click="ctrl.r ...

Sending an image using AngularJS to a WCF RESTful service

This particular query has been raised numerous times, and I have extensively researched on Google (primarily stackoverflow), but none of the suggested solutions have worked for me. My goal is to upload an image (base64) to my WCF Service using angularjs. ...

What is the best way to perform this task in Angular2?

I am currently working with three arrays: tables = [{number:1},{number:2},{number:3},{number:4}]; foods = [ {id:1, name:'Ice Cream'}, {id:2, name:'Pizza'}, {id:1, name:'Hot Dog'}, {id:2, name:'Salad'} ]; o ...

JavaScript: function that operates asynchronously

I am new to JavaScript and encountered some issues with async functions. I have a function that fetches data from MongoDB by creating a promise, but it returns a collection with an empty object. async function getRating(item, applicant) { let arr = await ...

Exploring Error Handling in AngularJS and How to Use $exceptionHandler

When it comes to the documentation of Angular 1 for $exceptionHandler, it states: Any uncaught exception in angular expressions is passed to this service. https://code.angularjs.org/1.3.20/docs/api/ng/service/$exceptionHandler However, I have noticed ...

Exploring the documentation of node.js with doxygen

When it comes to my C projects, I make sure to document them using Doxygen. Recently, I delved into the world of NodeJs and attempted to document .js files with Doxygen, but unfortunately, no output was generated. Despite my efforts to search for answers ...

Revamp the style of the date field in a Material UI dialog

I'm currently working on a React project where I am using Material-UI's date picker component to display date items. However, I find that the default style does not meet my requirements. I would like to use a selector for displaying dates in the ...

What causes compatibility issues between JEST and import statements in NEXTJS?

Just starting out with unit testing in JavaScript and I'm attempting to create a unit test for a Next JS project. However, when running the test, I encountered the following error: Code: import {isBase64} from '../../service/base64-service&a ...

What is the best way to eliminate brackets from JSON data?

I am facing an issue with my groovy script where the failedForm variable is being set to [Failed] instead of "Failed" when I parse my JSON. Removing the first pair of [] from the input JSON fixes the problem and sets failedForm correctly to " ...

What is the best way to implement JQuery in order to trigger an event in a text box whenever the user hits the "enter

Also, refrain from submitting the form if the user hits enter in THAT PARTICULAR input field. ...

What is the best way to utilize AngularJS to make an HTTP PUT request while including an ID?

I've successfully developed a Restful API in Python that interacts with my database and a table named groups. Currently, I have scripts for GET & POST operations, and now I'm working on creating a script for PUT to update a group. In the HTML doc ...

The issue arises in Selenium IDE when a variable is mistakenly identified as a string instead of a

Hey there, I've encountered an issue while using Selenium IDE. I'm trying to increment a variable by two, but instead of performing numerical addition, it seems to be concatenating strings. <tr> <td>store</td> <td> ...

Leveraging jQuery selectors to manipulate data received from an Ajax response

I am encountering an issue with an Ajax call and response. Previously, I had a block of regular javascript code that successfully transformed my select element into a select2 widget. However, when I attempt to convert the select element into a select2 usi ...

What is the method for pulling information from MySQL and presenting it on a website using Node.js?

Currently, my goal is to retrieve data from MySQL and showcase it on my HTML page. The code snippet in server.js looks like this: const path = require('path'); const express = require('express'); const bodyParser = require("body-pa ...

NPM is having trouble locating a shell script

An error is encountered when running npm run build: '.' is not recognized as an internal or external command, operable program or batch file. Here is the npm file that contains relevant scripts: "scripts": { "postinstall": "jspm instal ...

AngularJs Application Encountering Issues with Loading/Installing Google Maps API

I'm attempting to integrate Google Maps into my Angularjs app following the instructions provided here: http://angular-ui.github.io/angular-google-maps/#!/use After meticulously following all the steps, I encountered the following error: https://i.s ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

A guide on retrieving an object property in keen.io

When using the extractions API in keen.io, I'm facing an issue where specific properties that are objects are not being retrieved. curl "https://api.keen.io/3.0/projects/PROJECT_ID/queries/extraction?api_key=READ_KEY&event_collection=COLLECTION_N ...

Transferring information from nodejs/express to frontend JavaScript

I am faced with a challenge regarding accessing the 'data' sent from my backend server in my frontend js. Can anyone guide me on how to achieve this? Express ... app.get("/", (req, res) => { res.render("home", {data} ); }); ... home.ejs ...