whether you need a cache factory or a regular object

As I embark on creating a mid-sized Angular application, one of my requirements is to store data and utilize it at the end of the user journey for sending to the server (as per company security policy regarding customer data transport). As a relatively new Angular developer, I have been exploring various approaches and have concluded that utilizing a "dataFactory" or service would be the best way to go in order to maintain cleanliness in the app without cluttering it with a "master controller," etc.

My specific query pertains to whether I should simply use a normal variable within this service to assign key:value pairs, or if it would be more optimal to create a cacheFactory within the service to store the data. What are the advantages and disadvantages of each approach?

Answer №1

To effectively manage your data, it is recommended to create a dedicated service.

It is widely acknowledged that global variables are not good practice - the same principle applies to using a normal object buried within your code.

A possible solution is outlined below:

// service
myApp.service('controllerSharingData', function() {
  var __variables = {};

  return {
   get: function(varname) {
    return (typeof __variables[varname] !== 'undefined') ? __variables[varname] : false;
   },
   set: function(varname, value) {
    __variables[varname] = value;
   }
  };
});

// controllers
myApp.controller('IndexCtrl', function($scope, controllerSharingData) {
  controllerSharingData.set('toto', 'hello world');
});

myApp.controller('ListCtrl', function($scope, controllerSharingData) {
  alert(controllerSharingData.get('toto'));
});

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

Manipulate CSS Properties with Javascript Based on Dropdown Selection

I am currently working on implementing a feature that involves changing the CSS property visibility: of an <input> element using a JavaScript function triggered by user selection in a <select> dropdown. Here's what I have so far in my cod ...

Access the Angular element in the view with jQuery

I'm fairly new to Angular and I have a feeling that there's a concept I'm not quite getting. Here's what I'm trying to achieve: I want to load the main view, then click a button on the main view to load a different view. Once the ...

Creating Pop-up Dialog Boxes in WebForms Using jQuery

I have implemented a Plugin in Webforms using jQuery UI dialog. Since I have a Content Place holder on my Form, I had to modify the code as shown below: <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <link rel="stylesheet" ...

The customized cursor image fails to load after switching the application URL from http to https

After implementing a redirect from http to https in my application, I encountered an issue with custom cursor images not displaying as intended. Prior to the redirect, the custom cursor images worked fine and were visible on the page. The URL for these cur ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

What could be the reason why I am unable to load the ejs file?

https://i.stack.imgur.com/91bPg.png Issue: Unable to find the "index.ejs" view in the views directory ...

Encountering Undefined Object Error in Angular Framework

I just completed an upgrade to Angular and encountered an issue with the error message 'object is possibly undefined'. I have tried multiple solutions after doing some research online, including using 'if' statements, null coalescing, i ...

What is causing the chat-widget to display a null value for the style read property?

Could someone assist me with hiding the Widget-chat? I keep getting an error that the property of style is null. Any help would be greatly appreciated. Thank you in advance. document.getElementById("chat-widget").style.display='none'; ...

Is there a way to transform time into a percentage with the help of the moment

I am looking to convert a specific time range into a percentage, but I'm unsure if moment.js is capable of handling this task. For example: let start = 08:00:00 // until let end = 09:00:00 In theory, this equates to 100%, however, my frontend data ...

Alternative to Webpack for modifying global variables in preloaded modules

Is there a way to shim moment.js in webpack similar to how it is done in browserify? I have developed a widget using npm and webpack, which will be included in another application. The other app already has moment.js loaded via a script tag. I want to av ...

Which free and publicly accessible JSON image API is available for testing JSON requests?

Recently, I've been experimenting with AngularJS and am eager to incorporate some images using free APIs. While exploring options, I came across Flickr but was discouraged by the registration requirement for app usage. I am seeking a more accessible s ...

Creating a CSS3DObject with clickable functionality

Currently, I am utilizing the THREE JS CSS3DRenderer in an attempt to have a CSS3DObject update its position.z when clicked. Below is the code I am working with: var element = document.createElement("div"); element.style.width = "90px"; element.style.heig ...

Continuing to use a function multiple times may lead to a type error as it is not a

My program is designed to be a quiz where users have to answer questions. After answering, they will see a summary and then get the option to submit or redo the questions. The issue arises when users choose to redo a question. Upon redoing it, the summary ...

Triggered by each user interaction, the callback function is activated

I need to add a timeout feature to my AngularJS web application. Each time a user interacts with the site, a timer is set for 10 minutes. Once this timer runs out on the client-side, a request is sent to the server signaling a timeout. What is the best wa ...

The $apply method is behaving unexpectedly when attempting to add new data

I'm struggling to display new data instantly after an HTTP request without reloading the entire page. I came across using `$apply` from AngularJS for this purpose, but I can't seem to get it working as expected. Here is the code snippet in the c ...

Hiding a Material-UI raised button during printing: Tips and tricks

On my web page, there is a button that initiates a print using the window.print() method in JavaScript. However, when I preview the print, the button that triggered it is still visible. Is there a way to hide this button either after it's been clicked ...

Issues with Angular and Bootstrap: ng-hide functionality not functioning correctly

I am struggling to grasp the concept of the ng-show angular directive as it is not functioning correctly for me. Despite following some examples I found online, I cannot seem to change the boolean value in the controller like they suggest. Instead of using ...

Form submission using AJAX is failing to send the data correctly

I've been struggling with this particular piece of code for days now, and any assistance would be greatly appreciated. The issue I'm facing is that the script successfully calls the PHP file upon hitting the submit key, but it fails to post the ...

Tips for using conditional rendering with React and TypeScript

Issue with Conditional Rendering in TypeScript It seems like I might have encountered a problem with the way I declare my components. Take a look at this TypeScript snippet: import React, { FunctionComponent } from 'react'; export const Chapte ...