Monitoring changes to localstorage in AngularJS

How can I monitor changes to localStorage using $watch?

I have created a factory to simplify setting and getting values

.factory('$localstorage', ['$window', function($window) {
    return {
        set: function(key, value) {
            $window.localStorage[key] = value;
        },

        get: function(key, defaultValue) {
            return $window.localStorage[key] || defaultValue;
        },

        setObject: function(key, value) {
            $window.localStorage[key] = JSON.stringify(value);
        },

        getObject: function(key) {
            return JSON.parse($window.localStorage[key] || '{}');
        }
    }
}]);

In my controller, I am utilizing the factory like this:

.controller('CodesCtrl', function($scope, $localstorage) {
    $scope.codes = $localstorage.getObject('codes');
    ...

In another controller, data is being added to localStorage. I want to update the view as soon as there are changes in localStorage.

I have come across suggestions to use ngStorage, but I prefer avoiding that if possible.

Is it feasible to achieve this using $watch? If so, could someone guide me in the right direction?

Answer №1

To monitor changes in a specific value, you can create a $watch function that triggers whenever that value is updated.

$scope.$watch(function(){
  return $localstorage.getObject('codes');
}, function(newCodes, oldCodes){
  $scope.codes = newCodes;
});

It is important to conduct performance testing on this function as it will be invoked frequently.


An alternative approach is to utilize events for updating the codes only when necessary.

In Controller A:

var codes = updateCodesAndStoreInLocalStorage(); // <That part's up to you
$rootScope.$emit('codesUpdated', codes);

In Controller B:

$rootScope.$on('codesUpdated', function(event, codes){
  $scope.codes = codes; //Utilize localStorage for storage purposes only, not for communication.
});

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

AngularJS encountered an error while attempting to load a template: [$compile:tpload]

After developing my angularjs example app in my netbeans ide based local server, I encountered an issue when I tried to move the application to an nginx server. The browser displayed the following error message: Error: [$compile:tpload] Failed to load tem ...

Create object properties as optional, declare them afterwards, and access them without needing to verify

I'm wondering if there's a way to work around type definitions. Let me provide an example to clarify my question. Suppose I want to define a type that consists of a large object containing multiple objects: type BigObject = { dom: HTMLElement, ...

Utilizing React's createRef() for Enzyme testing

I am currently using the new React.createRef() api in one of my components. I am trying to figure out how to test if document.activeElement is equal to the current ref component. Here is the component code: export class Automatic extends Component { c ...

Exploring VueJS watchers: How to get started?

Struggling to grasp the concept of Watchers in VueJS, particularly when trying to implement them for tracking tab changes and resetting values. Even though I have set up a watch with parameters like `oldValue` and `newValue`, their usage remains unclear to ...

Break down a lengthy controller into smaller controllers within AngularJS

As I tackle a complex application, I've noticed that each controller contains over 2000 lines of code. Can someone recommend a strategy for breaking up the code into smaller controllers and using them as dependencies in the main controller? ...

Using Knex to Generate a Migration Including a Foreign Key

I attempted to use the code from this link in order to create a foreign key: how to do knex.js migration However, an error occurred at this line of code: table.bigInteger('AddressId') .unsigned() .index() .inTable('Address&apos ...

The variable req.body.Dates has not been declared

I am currently working on a project that involves dynamically populating two drop down menus using SQL Server. Depending on the selected items, I need to load a specific ejs template using AJAX. My goal is to load data based on the selected criteria. For e ...

Execute a single test from a particular test suite using Jest

Within my file named "test-file-1", I have several describes (test suites) with distinct names, each containing tests that may share similar names across different test suites. In order to run a single test suite or test, I enter the following command: n ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Loading Ajax content on a webpage

Recently, I've been impressed with the layout of Google Play Store on a web browser. I am eager to replicate that same smooth browsing experience on my own website. Specifically, I want to create a feature where selecting a category or item doesn&ap ...

Selecting a language by clicking on it

I recently designed a bootstrap navigation bar for my website and incorporated a language selection dropdown menu into it. <li class="nav-item dropdown"> <a class="nav-link dropright" href="#" id="navbarDropdown" role="button" data-toggle="dr ...

Styling an exponential number in a table header using Vuetify

I am looking to replace the default header 'number' with a custom HTML header while using vuetify for displaying a data table. My current setup looks like this: headers: [ {text: 'number', value: &a ...

Leveraging dynamic visuals for your Twitter metadata image

My Twitter application automatically posts the current title being broadcast on my web radio every 20 minutes. It includes details like the artist, number of listeners, and playlist, but does not display album covers. To work around this limitation, I am ...

Reset input value when adding or removing inputs dynamically

Currently, I have an input element that has the capability to clear its value when a button is clicked. Additionally, this input can dynamically add or remove input elements. However, I am facing an issue where after adding an input element, the clear butt ...

How to manage the state when multiple forms are generated by clicking a button

I am currently working on a feature that allows users to add multiple addresses, with a limit of 3 additional addresses in addition to the default one that cannot be removed. For this specific case, each address consists of a street name and city. My cha ...

Error: Authorization token is required

For email confirmation, I am utilizing JWT. An email is sent to the user with a URL containing the token. Here's an example of the URL received by the user: http://localhost:3000/firstlogin?acces_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI ...

Is it possible to directly call the Watch function from the controller?

Is it possible to manually trigger the watch function in the controller? Requirements: There are currently two nested tree structured checkboxes in AngularJS - one for carriergroups and another for modes. The mode values are dependent on the selected car ...

What is the significance of using the "why" in the href property within the

I need help understanding why the plus "+" is used before and after myUrl in the function .not. Even though it works fine with or without the +, I am curious about why it was included in the code snippet. <script type="text/javascript"> $(documen ...

Mapping nested values from a Typescript object to properties of a JSON object

Within the scope of a current project I am involved in, we have opted for utilizing the Angular toolset identified as formly to dynamically generate our forms. The present configuration of the form is hardcoded into a Typescript object denoted as mockForm ...

When scrolling, the fixed menu bar at the top of the page is making the content below jump

I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows: $(window).scroll(function () { if ($(window).scrollTop() > 175) { $('#loca ...