Attempting to replace an AngularJS object with another service results in it being reinitialized upon using ctrl + f5 in the application

In my AngularJS application, I have two services. One service is used to declare objects with default values, while the other service is responsible for assigning new values to those objects. Everything works fine in the controllers after rewriting, but when I refresh the browser using Ctrl+F5, the objects are reinitialized to their default values.

I need assistance in resolving this issue.

The functionality works as expected initially, but upon refreshing using Ctrl+F5, it resets to the default value.

var appl = angular.module('app');
appl.service('service1', ['$rootScope', '$modal', function($rootScope, $modal) {
    this.prefs = {
        rememberMe: false,
        popIt: function() {
            $modal.open({       
                templateUrl: "views/flag-message.html",
                controller: "flagMessageCtrl",
        });
        }
    };
}]);


var appl = angular.module('app');
appl.service('service2', ['$rootScope', '$scope', 'service1', function($rootScope, $scope, service1) {  

        service1.prefs.rememberMe = true;

}]);

var appl = angular.module('app');

appl.controller('DemoCtrl', ['$scope', 'Restangular', 'service1', function ($scope, Restangular, service1) {

alert(service1.prefs.rememberMe);

}]);

Answer №1

Forget about dealing with cookies or writing cumbersome code in AngularJS; simply store your data directly in the browser using window.name.

By utilizing window.name, your stored values will remain intact within the same browser tab even when the page is refreshed.

Answer №2

It is important to note that hitting ctrl+f5 will reload your entire angular app, which is the intended behavior. If you want certain settings to remain persistent, it would be beneficial to utilize a library specifically designed for that purpose.

An excellent option to consider is angular-storage by Auth0. This library allows you to store values/settings across different browser storage options such as local, session, and cookies, ensuring consistency between sessions.

Answer №3

Once a page is refreshed, it will reset and all JavaScript context will be lost.

To prevent data loss, you can utilize localStorage which persists even after the browser is closed.

$localStorage.item = []

Check out the DEMO here!

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

Exploring the map function in Angular and native JavaScript

Still getting the hang of angular, so there might be something I'm overlooking. I have a model containing a collection of objects with their own properties, and my goal is to generate a csv value based on the Text property of each object. I've ex ...

Challenges when replacing the use of localhost with the actual IP address in the ionic service.js file

I'm currently working on deploying my Ionic v1 application. One of the requirements is to change the baseURL from localhost:3000 to myip:3000. Before (works): angular.module('conFusion.services', ['ngResource']) .constant( ...

Angular2 - Utilizing Promises within a conditional block

I'm currently facing an issue where I need to await a response from my server in order to determine if an email is already taken or not. However, I am struggling to achieve this synchronously. TypeScript is indicating that the function isCorrectEmail( ...

Django: Is there a way to modify the PayPal script for pay upon arrival?

I currently do not wish to accept online payments on my e-commerce site. Instead, I would like the courier to handle package delivery and collection of fees. How can I modify the PayPal script to bypass validations and only register payments upon arrival? ...

Establishing the maximum width of a Vuetify expansion panel component

https://i.sstatic.net/QqKVv.png I'm currently in the process of developing a webpage using vuetify and nuxt. My main focus right now is adjusting the max-width property of the expansion panel UI component (https://vuetifyjs.com/en/components/expansio ...

Implement the color codes specified in the AngularJS file into the SASS file

Once the user logs in, I retrieve a color code that is stored in localstorage and use it throughout the application. However, the challenge lies in replacing this color code in the SASS file. $Primary-color:#491e6a; $Secondary-color:#e5673a; $button-color ...

Finding out which carousel the user is currently engaging with in the Slick Carousel can be accomplished by following these steps

I am struggling with applying a class to the carousel container when the first slide is active in a page that contains multiple Slick carousels. Is there a way to update the code below so that the class is only applied to the specific carousel the user is ...

Storing information in local storage as JSON using AngularJS

I am working on a form with the following fields: <form ng-submit="addState()"> <input ng-model="text1" type="text"> <input ng-model="text2" type="text"> <input ng-model="text3" type="text"> ...

What is the best way to create a universal variable that can be accessed across all routes in an Express/

Exploring the world of nodejs and express, I have turned to the Parse API for my backend database needs. At the moment, I have an ajax post triggered on page load to one of my routers /getuser, which retrieves the current user if they are logged in. I am ...

What is the best way to retrieve the value of the "Observer" object?

I am a user of Vue.js and I have the following data in this.suspendedReserveMemo: this.suspendedReserveMemo [__ob__: Observer]650: "memo3"651: "memo4"652: ""653: ""654: ""655: ""656: ""657: ""658: ""659: ""660:""661: ""662: ""length: 663__ob__: Observer {v ...

Ways to eliminate the Vuetify append-icon from the sequential keyboard navigation

In my Vue.js application using Vuetify, I have implemented a series of password fields using v-text-field with an append-icon to toggle text visibility. Here is the code snippet: <v-text-field v-model="password" :append-icon="show1 ? 'mdi-eye& ...

Implementing Google Places reviews on a website with the help of JavaScript

Struggling to display the Google reviews for my company on our website, I can't seem to make it work. I've attempted to use this code: <script> $(function() { var people = []; $.getJSON('https://maps.googleapis.com ...

Steps for performing position by position sorting within an array of arrays of numbers using the Lodash library

My task involves sorting an array of strings: ['1.2.3', '1.5.2', '1.23', '1.20.31'] I am looking for a way to sort the array by splitting each string separated by dots, such as 1.2.3 into ['1','2&apo ...

Issue with scrolling in angular-ui-bootstrap modal on Apple devices with the mobile web app capability enabled

I've encountered a problem with a basic to-do list web application that I'm currently developing. In order to enable the iPhone standalone launch feature, I have included the following code: <meta name="apple-mobile-web-app-capable" content=" ...

The browser is not displaying the results from Mongodb, yet they are appearing in the console

I am currently using the following code for my router: let mongoose = require('mongoose'); // connecting with our model let ByProduct = require('../models/Byproduct') router.get('/',(req,res,next)=>{ ByProduct.find().th ...

Node.Js powers a multilingual blogging experience like no other!

Greetings! I have built my entire site using Node.JS and I am currently working on developing a blog for it. I am planning to have the blog available in English, Spanish, and Portuguese languages. The technologies I am using include node.js, mongodb, expr ...

Issue with Protractor locating element even though everything appears to be in order

I'm having trouble locating this element with Protractor. It's really frustrating me. I double-checked in the dev console and the element definitely exists. Any suggestions on why it's not being found? <download path="api/backup_jobs/e ...

Retrieve data from the endpoint using Routing.generate to access the JSON route

My goal is to retrieve data from the database within a Symfony controller, encode the response into JSON format. The code snippet for this functionality is shown below: /** * @Route("/jsondata", options={"expose"=true}, name="my_route_to_json_data") */ ...

Is it possible to swap the src of the Next.Js Image Component dynamically and incorporate animations in the

Is there a way to change the src of an image in Nextjs by using state and add animations like fadein and fadeout? I currently have it set up to change the image source when hovering over it. const [logoSrc, setLogoSrc] = useState("/logo.png"); <Image ...

JQuery horizontal navbar hover animations

Looking to design a simple navigation bar that displays a submenu when hovering over a link. The issue I'm facing is that the submenu disappears when moving from the link to the submenu itself, which is not the desired behavior. How can this be fixed ...