Maintaining data after page reload in Angular

angular.module('eventTracker', [])

.controller('MainCtrl', ['$scope', 'Event', function($scope, Event){
    $scope.eventData = {}
    $scope.onSubmit = function(){
        Event.Add($scope.eventData)
        $scope.eventData = {}
    }
}])

.factory('Event', function(){
    if (!eventList) {
        var eventList = []
    }
    return {
        Add: function(event){
            eventList.push(event)
        },
        List: eventList
    }
})

Hey everyone, I'm facing a challenge with persisting eventList data after a page refresh. I'd appreciate any insights on why this might be happening! I prefer not to use cookies, local storage, or rootscope and thought my service was correctly set up. Any suggestions would be greatly valued! Everything works perfectly except that upon refreshing the page, all previous data is lost.

Answer №1

Whenever you hit the refresh button on your browser, any data stored in Javascript variables will be lost. To avoid losing this data, it is important to store it in a database and retrieve it using methods such as AJAX when the page loads.

If you want to navigate between different 'pages' in your AngularJS application, utilizing routing and multiple views is the way to go. This approach allows you to switch between pages while retaining all the data stored in your service.

Learn more about routing in the AngularJS tutorial here.

Answer №2

When it comes to managing cross page state, you have a few options:

On the server side - persisting/retrieving data via ajax

On the client side:

  • Using cookies
  • Utilizing other state stores like Flash (which is now considered obsolete), HTML 5 local storage, or session storage
  • Implementing a third-party library like

If you only have small amounts of state data and none of the above methods are suitable, you could encode the state in URLs (e.g. as a query string parameter when navigating between pages). However, this approach can be quite cumbersome for anything beyond simple scenarios.

Any data stored within the Angular app/scope/rootscope will be lost upon refreshing the page.

While this may seem inconvenient, it actually has its benefits by allowing you to clear out browser memory. While Single Page Applications (SPAs) are efficient, large SPAs can become bloated and vulnerable to crashes caused by a single faulty script. Breaking down a SPA into smaller mini applications offers numerous advantages.

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

Uncovering the key based on the value in MongoDB

I'm currently working with Node.js using the express framework and Mongoose for MongoDB, and I've got a query regarding efficient data retrieval. Imagine having a mongo document structured like this: test : {a:1, b:2, c:2, d:1}; While it' ...

I pressed the button but the globalCompositeOperation isn't working as expected. How can I make it function correctly to achieve the desired output like the second canvas?

<!DOCTYPE html> <html> <head> <title>Canvas Compositing Tutorial</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border: 1px solid"></canvas> <br> <butt ...

It appears that the setup function completes its execution before the onMount function is called in Vue 3

createApp({ setup() { let price = 0 onMounted() { // axios price = axios.response } return { price } } }).mount('#app') HTML <h6 id="app" class="mb-0"> ...

I'm unsure of my recollection on how to utilize the /* syntax in JavaScript

Hey there, I'm facing a little issue. Can someone remind me how to correctly use the /* in JavaScript when dealing with URLs? For instance: if(URL == "www.thing.com/"){} I can't quite remember where to insert the /* so that it applies not just ...

The pagination component in React with Material-ui functions properly on a local environment, but encounters issues when deployed

Looking for some assistance with a persistent issue I've run into. Can anyone lend a hand? [x] The problem persists in the latest release. [x] After checking the repository's issues, I'm confident this is not a duplicate. Current Behavior ...

The statement ""x=x || 4" will result in a `ReferenceError: x is not defined` because the

What is the reason behind receiving a ReferenceError: x is not defined error when using x = x || 4 or even x=(x||5), while var x = x || 4 operates as intended? ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

Make necessary changes to empty objects within a JSON array

Modify the null objects in a JSON array. I attempted to use map, but it did not update all the JSON objects. Here is an example of a JSON array: var response = { "code": null, "message": "Total 1 records found", "result": { "ordersList": [ ...

Retrieving information from nested JSON objects using JavaScript

I'm struggling with extracting data from a JSON array object. Despite trying to use Iterables & Iterators, I can't seem to grasp the concept. { '-LIDMHr69GLnq1Pyzt6o': { author_avatar: { image: 'https://lh3. ...

Will the package versions listed in package-lock.json change if I update the node version and run npm install?

Imagine this scenario: I run `npm install`, then switch the node version, and run `npm install` again. Will the installed packages in `package-lock.json` and `node_modules` change? (This is considering that the packages were not updated on the npm regist ...

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

The impact of React-router's history within the connect function of the react-redux provider

After successfully connecting my presentational-functional component to the redux store using the connect function, I encountered an issue regarding redirection upon triggering the getTask action or when apiGetTask has completed. I attempted to implement t ...

Navigate directly to a designated element in a React component without the need to scroll when clicking a link

When viewing a user's profile in React, clicking on an image currently scrolls to that specific image within the entire images page. However, I am looking to modify this behavior so that it navigates directly to the image element without any scrolling ...

What are some ways to style an image that has been added using JavaScript using CSS?

I utilized a JavaScript function to add an image, which looked like this: function show_image(src) { var img = document.createElement("img"); img.src= src; document.body.appendChild(img); } But when I attempt to change its style using CSS: img ...

Guide to seamlessly navigating to an element using a hash in NuxtJS

My aim is to create a smooth scrolling anchor link menu using Nuxt.js, where the user can click on a link and be directed to the corresponding page section. However, I'm facing a dilemma as there are multiple approaches to achieve this functionality, ...

jqGrid: What could be causing the events I defined for grid edit to not fire?

I've been attempting to make in-line edits on a grid, but it seems like none of the events connected to those edits are being triggered. I am specifically looking to use afterSubmit: so that it triggers after the user has edited the Quantity field in ...

The SSE emitter sends out multiple signals, but occasionally the browser fails to receive them

When setting up an event emitter in a node.js/express application, I noticed that the events emitted are sometimes received multiple times by the front-end listener. Although I can confirm that emit is only called once, the same event gets emitted up to 4 ...

Image renders only on a single page in Express.js

I am facing an issue while attempting to display an image on multiple pages using Pug and Express. The image should be visible on the routes '/', 'data', and 'update'. While it is successfully displayed on the root '/&ap ...

What is the technique for anchoring elements at the top of the page when scrolling?

There is a common design feature where the sidebar on the left starts at a lower position on the page, but as you scroll it moves up to the top and remains fixed in place instead of disappearing off the screen. This is a popular design trend that I have ...

Is the textarea's shape out of the ordinary?

Most textareas are typically rectangular or square in shape, similar to this: However, I am interested in having a custom-shaped textarea, like the example below: Is it feasible to achieve? ...