AngularJS/Restangular index-based extraction of JSON data

I have developed an application that takes input for quotes (purity, weight, total) and stores it in the $scope.quote array:

// Controller action //
$scope.quote.push({ 
  total: ((($scope.karat * $scope.spot) * $scope.percentage) / 20) * $scope.estimatedWeight,
  karat: $scope.karat * 100,
  description: $scope.description,
  actualWeight: $scope.actualWeight,
  estimatedWeight: $scope.estimatedWeight,
  percent: $scope.percentage * 100,
  spot: $scope.spot
})

Additionally,

// Factory //
app.factory('quoteFactory', function() {
  var quote = [];
  var factory = {};
  factory.getQuote = function () {
return quote;
  };
return factory;
})

The process involves posting/saving the quote upon completion:

$scope.save = function() {
  var now = $scope.getDate();
      $scope.quote.push({
        createdOn: $scope.getDate()
      })
    Restangular.all('quote').post($scope.quote).then(function(quote){
      $location.path('#/scrap')
    }); 
  };

Although, when I attempt to access the quote JSON for listing or editing, I am unable to retrieve all the necessary information due to the JSON structure.

{
"0": {
    "total": 401.79040000000003,
    "karat": 74,
    "description": "Rings",
    "actualWeight": 12,
    "estimatedWeight": 11,
    "percent": 80,
    "spot": 1234
},
"1": {
    "total": 560.7296,
    "karat": 56.8,
    "description": "Test",
    "actualWeight": 22,
    "estimatedWeight": 20,
    "percent": 80,
    "spot": 1234
},
"2": {
    "total": 48.5625,
    "karat": 92.5,
    "description": "Testing",
    "actualWeight": 80,
    "estimatedWeight": 75,
    "percent": 70,
    "spot": 20
},
"3": {
    "createdOn": "2013-11-26T21:26:42.253Z"
},
"_id": {
    "$oid": "52951213e4b05f03172f14e7"
}
}

Each index corresponds to a line item of the quote along with the createdOn information. I am exploring ways to access all the line item details without having to iterate through each individual index.

I have considered using lodash/underscore, as well as restructuring the backend, but I am unsure of the best approach to take at this point.

Full project code available on GitHub

Answer №1

Given the limited information available about how your backend system operates, I'm assuming the issue lies in JSON generation.

To address this, I recommend modifying the way Angular sends data to the server. Here's an example of how you can update the Save function:

$scope.save = function() {
  var url = 'http:127.0.0.1:3000/url/you/send/your/data/to',
      json = JSON.stringify($scope.quote);

  $http({
    method: 'POST',
    url: url,
    data: json,
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(function(response) {
    $location.path('#/scrap');
  });
};

This approach provides more control over how data is handled, ensuring proper conversion to JSON using the .stringify() method of the JSON object.

It's important to note that objects typically have an id property for server synchronization, representing database IDs rather than client array indices. This maintains consistency between client and server data models.

For assistance with client-side operations, consider exploring Angular Resource, a useful library compatible with Angular.

For older browser support when using JSON.stringify(), consider implementing Crockford's JSON2.js library.

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

What is the best way to test a JavaScript function using Jest?

Just diving into JS, Express, Node, Jest... I'm tackling a new challenge where I have to work on an unfamiliar code base. The task at hand is to enhance its functionality and incorporate testing. The existing code contains a function for creating a ne ...

Creating reusable functions in VueJS that can be accessed globally by all child components

Looking for assistance in setting up a universal function that can be accessed across all my Vue files. For example, when using this code snippet in a Vue file: @click="ModalShow.show('my-create')" I have defined the following constan ...

Tips for employing duplicated HTML on a webpage

I have developed a main menu for my website using html and css. It seems cumbersome to manually copy and paste this menu into every single file or page on the website whenever I make edits. Is there a way for this main menu to automatically appear on every ...

Tips for automatically refreshing a page after submitting a form

I have a template with two components - a filter and a request to the API. I am wondering if it's possible to update the values of the request component after submitting the filter. On the main page, the request component has default values. When a u ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

Krajee Bootstrap File Input, receiving AJAX success notification

I am currently utilizing the Krajee Bootstrap File Input plugin to facilitate an upload through an AJAX call. For more information on the AJAX section of the Krajee plugin, please visit: Krajee plugin AJAX The JavaScript and PHP (CodeIgniter) code snippe ...

Setting up datatables with angular and personalizing the toolbar

Visit this link for the code snippet $scope.overrideOptions = { "bStateSave": true, "iCookieDuration": 2419200, /* 1 month */ "bJQueryUI": false, "bPaginate": true, "bLengthChange": true, "bFilter": true ...

Guide to finding your way to a specific section in React

I attempted to navigate to a particular section within a page. I also tried to include an id in the component, but it didn't function as expected <Login id ="login_section > ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

Leveraging a single Axios request across various components

My current setup involves making a simple Axios call in this way: .get('https://myAPI.com/') .then(response => { this.info = response.data }) Subsequently, I utilize a v-for array loop on my components to display the retrieved data. ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

The function is failing to provide a return value

In the Game.js file, there is a function that I am working on Game.prototype.onClick = function(event){ var x = event.x; var y = event.y; if (this.blueDeck[0].contains(x, y)) alert("Blue Deck Clicked"); } The OnClick function is ca ...

Avoids processing all grid rows in asp.net code

I am encountering a problem and would appreciate some assistance. The issue I am facing is related to a grid I have created. While the values are calculated correctly in the first row of the grid, the calculations do not seem to have any effect on the ot ...

Events for focusing and blurring top level windows

I'm encountering an issue with a basic frameset setup <frameset rows="100, 200"> <FRAME name="listener" src="frame1.html"> <FRAME name="content" src="http://www.someexternalurl.com/"> </frameset> Within the listener ...

Struggling to fill in fields using express and Mongodb

I am facing an issue with populating the fields of two models, Post and User. const PostSchema = new Schema({ text: { type: String }, author: { type: mongoose.Schema.Types.ObjectId, ref: 'user' } }) cons ...

Transforming Java Properties Into Nested Map to Obtain JSON Format

For a fun project and internal tool development, I am working on converting a Java properties file to a JSON hierarchy. foo.bar=15 foo.lots.dir=/tmp/test foo.baz.host=localhost foo.baz.port=333 I have successfully converted it to a Scala map, here' ...

Creating a custom component results in an extended duration to 'eliminate' its children

1I am currently facing an issue with a time-table component created using vue.js. It contains approximately 200 nested child timeline components, making it quite complex (I wanted to share an image but lacked the reputation to do so). The main problem lie ...

Is there a way to search for multiple items using just one search term?

On my app, there is a search bar that currently only looks up data for one specific attribute. For example, if I type in "Hammer," it only searches for Tool names. Now, I need to expand the search functionality to accommodate different types of strings. F ...

The combination of Spring Boot and Angular's routeProvider is a powerful

I have been working on a project using Spring Boot, REST, and AngularJS. While I successfully implemented the back end with REST, this is my first time using AngularJS. Despite watching numerous tutorials and following them step by step, I am still facing ...