Efficiently accessing and displaying nested models in AngularJS

Currently, I am in the process of developing a website that involves numerous relational links between data. For instance, users have the ability to create bookings, which will include a booker and a bookee, as well as an array of messages that can be associated with a booking.

An illustration in JSON format would look like this...

booking = {
  id: 1,
  location: 'POST CDE',
  desc: "Awesome stackoverflow description."
  booker: {
    id: 1, fname: 'Lawrence', lname: 'Jones',
  },
  bookee: {
    id: 2, fname: 'Stack', lname: 'Overflow',
  },
  messages: [
    { id: 1, mssg: 'For illustration only' }
  ]
}

My main question is, how should one structure this data in an Angular app? Furthermore, how would you retrieve it from the server?

From my perspective, there are a few approaches.

Retrieve all data at once from the server

In this scenario, I would depend on the server to serialize the nested data and directly utilize the provided JSON object. The drawbacks here are that I wouldn't know which users are involved when requesting a booking or similar objects, making caching impossible, resulting in pulling a large amount of data each time a request is made.

Retrieve booking with booker/bookee represented as user ids

Here, I would employ promises for my data models and have the server send back an object like...

booking = {
  id: 1,
  location: 'POST CDE',
  desc: "Awesome stackoverflow description."
  booker: 1, bookee: 2,
  messages: [1]
}

This object would then be passed to a Booking constructor, where I would resolve the relevant (booker,bookee, and message) ids into data objects using their respective factories.

The downside here is that multiple ajax requests are made for a single booking request, although it allows for caching user/message information.


To summarize, is it best practice to rely on a single ajax request to gather all nested information at once, or use various requests to fill in additional details after receiving the initial response.

It's worth mentioning that I'm utilizing Rails 4 (maybe Rails would better suit a single request approach?)

Answer №1

In an effort to combine the best of both worlds, I am implementing a system where all my resources will have a base class with a custom resolve function. This function will identify which fields in each specific class may need resolution. An example resource function is outlined below...

class Booking
  # other methods...
  resolve: ->
    booking = this
    User
      .query(booking.booker, booking.bookee)
      .then (users) ->
        [booking.booker, booking.bookee] = users

This function will pass the values of the booker and bookee fields to the User factory, which has a constructor as follows...

class User
  # other methods
  constructor: (data) ->
    user = this
    if not isNaN(id = parseInt data, 10)
      User.get(data).then (data) ->
        angular.extend user, data
    else angular.extend this, data

If a value that cannot be parsed into a number is passed to the User constructor (accepts both string and numerical ids), it will use the User factory's get function to retrieve data from the server. If the value can be parsed into a number, it will assume the User object has already been serialized and extend the current object with the data provided.

This implementation handles caching invisibly and independently of how the server returns nested objects. It allows for modular ajax requests and prevents unnecessary data downloads through its caching system.

Once everything is set up, I will conduct tests to determine whether larger, chunked ajax requests or smaller modular requests, like the one described above, would serve the application better. Regardless, this approach ensures that all model data passes through angular factories, giving every record access to any prototype methods needed.

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 a Hyperlink that Navigates to Specific Content Within a

I have a situation where I am trying to link to sections on the page contained within collapsed fieldsets. My goal is that when a user clicks on this link, the page should scroll down and automatically expand the fieldset to display the content inside. E ...

The backspace key is unresponsive following the use of a jQuery class

Using a specific class for an input field: Here is the code for the input field: <?php echo $this->Form->input('duration', array('class'=>'input-large text-right number-field','value'=>'0&apo ...

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...

Tips for obtaining a specific sorting order based on a wildcard property name

Here's the structure of my JSON object, and I need to sort it based on properties starting with sort_ { "sort_11832": "1", "productsId": [ "11832", "160", "180" ], "sort_160": "0", "sort_180": " ...

Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code... function ajaxRequest() { var xmlhttp; var domainName = location.host; var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName='; url = url + domainName + ...

Simple steps for importing JS files in a web application

Upon examining the code snippet below: const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const cors = require('cors'); app.u ...

SSE and the power of NodeJS through Express

Having trouble receiving SSE events in the browser. This is the server-side code (using Express): app.all('/callme', function(req, res){ res.writeHead(200, { 'Connection': 'keep-alive', 'Content-Type&apo ...

Presenting a trio of distinct tables each accompanied by its own unique button option

I am attempting to create a functionality where there are 3 buttons and when a user clicks on one of them, it shows the corresponding table while hiding the other two. I have experimented with using getElementById to manipulate the display property of the ...

How can I resolve the issue of encountering the "Modal dialog present: If you navigate away from this page, any unsaved changes will be lost" message while using Internet Explorer with

Here's the code snippet I'm working with. While it successfully removes the alert box, it throws an error in the console: Exception in thread "main" org.openqa.selenium.UnhandledAlertException: Modal dialog present: If you leave this page, any c ...

Error message: It appears that the jQuery Ajax request is not being processed

I've got this snippet of code that sends a request and logs the results using console.log (I left out my key and sig). The issue is that it seems like the request is not being executed. Appreciate any help, I'm new to this and still in the lear ...

Guide to counting the number of image tags within a parent div and selectively removing them starting from a specific position

My dynamic image tag <img> is generated inside a div from the database using fetching. Here is how my HTML looks: <div class='forimgbox'> <p class='palheading'>Pals</p> <img src='userpic/2232323.p ...

Extract the HTML content from a website that is dynamically rendered using JavaScript

Follow this link to access a document in an open nutrition database: http://www.dabas.com/ProductSheet/Detail.ashx/124494 I am attempting to extract data from this page using xpath. The issue arises when I attempt to view the page source to identify the ...

Is there a way to display only the specific child div within the parent div using JavaScript without affecting the others?

   **** Sorry for the lengthy title **** Today I encountered a problem that I would like to discuss with all of you. When I click on a "COMMENT" button, instead of triggering JavaScript code to display a CHILD.div inside the corresponding ...

The mouseup event fails to trigger upon dropping a component with React-dnd

Currently, I am working on a project that requires drag and drop functionality using the React-dnd package. While I have been able to successfully implement this feature, I am facing an issue with the target component where draggable items are supposed to ...

Is it possible that binding a ref is not functional in vue.js?

Whenever I use v-bind to bind an element reference with :ref="testThis", it appears to stop functioning. Take a look at this working version: <template> <div> <q-btn round big color='red' @click="IconClick"> ...

Why is Angular not functioning properly with nested ng-repeats?

I have utilized nested ng-repeat to iterate through all the values of objects. <tr class="" ng-repeat="(position, values) in chartResult.realData track by $index"> <td> <div ng-click="select(position)" ng-class="{selected: ...

Execute the code only if the variable is not null

I encountered an issue with my code: setInterval(function() { $.ajax({ url: url, success: function(data, count){ var obj = jQuery.parseJSON(data); var content = obj.results[0].content; }}) }, 2000) The code runs every 2 seconds an ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

How to display a conditional component in a single line with Material UI

I'm facing an issue with a component that is being reused multiple times. Here's the current output: |MyComponent1| |MyComponent2| Specifically, my condition is: if (a == 'One' || b == 'Two'){ <MyComponent data={data}/> ...

When trying to use setInterval () after using clearInterval () within an onclick event, the functionality seems

Can anyone assist me with an issue I am encountering while using the setInterval() function and then trying to clear it with clearInterval()? The clearInterval() works fine, but the automatic functionality of li elements with a specific class suddenly stop ...