Using Angular to share JSON data efficiently between controllers

Greetings everyone, I am a beginner in Angular and not very skilled with JavaScript. The issue I'm facing is that although this setup successfully fetches the JSON data, whenever I modify certain object properties, they revert back to their original state when I switch views and the controller reloads. Any advice or suggestions on how to tackle this problem would be greatly appreciated.

app.controller('MainCtrl', function ($scope, $location, Quiz) {
    $scope.quiz = {};

    Quiz.getQuestions(function(data) {
      $scope.quiz = data;
    });
});

app.service('Quiz', function($http) {
  this.getQuestions = function(callback) {
    $http.get('questions/questions.json').success(function(data) {
      if (callback) {callback(data);}
      return data;
    });
  };
});

Answer №1

Is the data from the $http get request in the function getQuestions() overwritten on subsequent calls? If it is, then maybe you can try this approach:

app.service('Quiz', function($http) {
  var _data;
  this.getQuestions = function(callback) {
    if (_data) {
       callback(_data); 
    }
    $http.get('questions/questions.json').success(function(data) {
      _data = data;
      if (callback) {callback(data);}
      return data;
    });
  };
});

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

Avoid mentioning the controllerAs alias in your directive

I'm facing an issue with the following code snippet. Here is the simplified version of the problem: <div ng-controller='AController as a'> <div a-directive></div> </div> In my JavaScript file, I have defined: a ...

Issues with CSS Modules not applying styles in next.js 13 version

Employing next.js 13.1.1 along with /app Previously, I had been handling all of my styles using a global.css, however, I am now attempting to transition them into CSS Modules. Within my root layout.js, there is a Header component that is imported from ./ ...

What is the best way to transmit data as a reply from a Node.js server to an AJAX client?

Currently, I am utilizing a function to transmit data regarding an HTML element as an object: function postItem(input) { $.ajax({ type: "POST", url: "http://localhost:8080", data: input, success: function(message) { Hconsole.log(&a ...

Errors encountered during the Angular project build

I need help figuring out what's happening. I keep getting the same error while trying to build my project. I've already attempted deleting typings, angular directory, and performing typings install but nothing seems to be working. All the necess ...

Angular 6 tutorial: Creating a dynamic side navigation bar with swipe and drag functionality using Angular Material/Bootstrap

I am currently working on implementing a vertical swipeable/stretchable side nav-bar with angular-material in angular 6. However, I have encountered an issue with mouse interactions for stretching the nav-bar. Below is the code snippet: Here is the HTML c ...

Error: The document object is not defined when attempting to access it within a

<script type="module" src="/scripts/navbar.js"></script> <script> async function fetchContent(e) { e && e.preventDefault(); const response = await fetch('https: ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...

Issue with SwiperJS not completely filling the height of a div

My issue relates to using swiperJS with multiple images, as I'm struggling to make it take the full width and height of the containing div. Despite applying styling like this to my images: .swiper-slide img { width: 100%; height: 1 ...

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

Ways to access UserProfile in a different Dialogio

For the implementation of a chatbot, I am utilizing Microsoft's Bot Builder framework. However, upon implementing an alternative path to the dialog flow, I noticed that the user's Profile references are getting lost. Here is the code snippet fr ...

Is it possible to implement JSON in place of SQLite for my Android application?

Currently, I am working on a basic android application that includes an activity dedicated to showcasing data extracted from a few tables in an online mySQL database. These tables are fairly straightforward and will not exceed 100 rows. In order for the a ...

The appearance of an unforeseen * symbol caused a

Having issues with this particular line of code, import * as posenet from '@tensorflow-models/posenet' The error 'Uncaught SyntaxError: Unexpected token *' keeps popping up, I have the latest version of Chrome installed and I've ...

What is the best way to retrieve a specific item from an array of objects stored in JSON format using React?

I have received a json file named data.json which contains multiple objects in an array. My goal is to extract the value of a specific key from each object. To achieve this, I am utilizing react redux to fetch these values and present them in a table forma ...

Having trouble obtaining information from the state with Pinia Store

Currently, I am delving into the world of the composition API and Pinia with Vue3. I am facing an issue while calling an external API to fetch data and store it in the state of my store. The problem arises when I try to access this state from my page - it ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

How can I create an efficient chat system using Ajax and settimeout without causing excessive virtual memory usage?

I'm in the process of creating a chat application using AJAX that fetches data every second with setTimeout. I have drafted a basic code where there is a number that increments each second by the number retrieved from the PHP page2. Upon testing it on ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

Move the modal dialog so it appears closer to the top of the page

I am facing a challenge with my jQuery modal dialog. While it is loading properly, I am restricted to using an older version of jQuery (1.12.4) and cannot upgrade it. My goal is to center the modal close to the top of the page, similar to how it is positio ...

End node.js once and for all

After starting my server using forever start start.js It ran normally. However, when I attempted to stop it with forever stopall The server was removed from forever list as expected Nevertheless, upon running lsof -i tcp:3000, my server still showed u ...

Javascript function fails to trigger when clicked

<body ng-app="starter"> <ion-pane> <ion-header-bar class="bar-dark"> <h1 class="title">AppifyLife</h1> </ion-header-bar> <ion-content> <center><div class="card" id="life"><h3>20< ...