What is the process of implementing session storage in an AngularJS directive?

I am trying to save values in Angular session storage within an Angular directive, but I am facing an issue where I only receive NULL. Can anyone provide assistance?

app.directive('myDirective', function (httpPostFactory) {
return {
    restrict: 'A',
    scope: true,
    link: function (scope, element, attr) {

        element.bind('change', function () 
        {
            sessionStorage.setItem("ID","I'm a value saved with SessionStorage");
            console.log(sessionStorage.getItem("SavedString"))

        });

    }
  };
});

Answer №1

To save the data, you can use ID as the key and retrieve it using SavedString. It should look like this:

        sessionStorage.setItem("ID","I'm a value saved with SessionStorage");
        console.log(sessionStorage.getItem("ID"))

:)

In addition, placing this logic in a directive may not be the best approach; consider moving it to a service instead.

Answer №2

Feel free to try out the following code snippet as well:

localStorage.key = "I'm an example of data stored using localStorage";
console.log(localStorage.key);

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

Notifying the chosen option using jQuery

I have been attempting to display an alert on the webpage based on the selected option. Unfortunately, it appears that my code is not functioning properly. This is what I have tried: $(document).ready(function(){ $("select.country").change(functio ...

Ways to verify the occurrence of a successful event following the execution of a save() operation on a model

Below is the snippet of code I am using to store extra properties in a model (specifically, the answer model) selectMedia: => # Post media to server @options.answer.id = @options.answer.get('_id') @options.answer.url = "/v1/answers/#{@o ...

The Bootstrap nav-link class functions perfectly in Firefox, smoothly guiding users to the appropriate section. However, it seems to be experiencing some issues

I am currently working on customizing a one-page web template and I don't have much experience with Bootstrap. The template can be found at . My issue is that the menu items are not functional in Chrome. When I click on any menu item, nothing happens ...

What could be causing my controller to show {{message}} instead of the message that was set up in the configuration

<!DOCTYPE html> <html> <head> <script src="js/angular.js"></script> <script src="js/Script.js"></script> </head> <body ng-app="LoginPage" ng-controller = "LoginPageController"> <form ...

Unexpected Token E encountered in the Twitter stream.on function

I'm currently in the process of setting up a search button on my web application that will pull all Twitter tweets related to the search input using the streaming API. Below is my client-side code: <form class="navbar-form navbar-left" role="sear ...

Retrieving parameters from a class that is handed over from the constructor to a function by leveraging the rest parameter feature

I am encountering an issue where the Method is not reading the values in the arguments, despite my attempts to pass each argument through the constructor into the method for encryption. Could someone please point out what I might be doing wrong? class A ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

Utilize or Bring in an external JavaScript file within Ionic 2

Currently working with Ionic 2 and Typescript Angular 2 and facing an issue. I need to utilize an external JavaScript file located at . How can I import or include this in my project? ...

Discord.js version 13 encountered an issue where it is unable to access properties of undefined while

Having trouble with creating a warn system that just won't work! I've tried various solutions but nothing seems to be fixing it. Would greatly appreciate any help! Error Log: [FATAL] Possibly Unhandled Rejection at: Promise Promise { <reje ...

Encountered an issue with resolving the module specifier while attempting to import a module

Whenever I attempt to import a module, I consistently encounter this error message Failed to resolve module specifier "mongodb". Relative references must start with either "/", "./", or "../". and I have searched ext ...

NodeJS not recognizing global variable causing it to return undefined

Can a global variable be defined in a node.js function? I wish to use the variable "ko" (declared in the getNumbers function) in other functions function getNumbers(callback) { result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", ...

JavaScript problem with setting values in 2D array

I am attempting to assign values to a 2d array at particular indices. During each iteration, all sub-arrays at the j index are being assigned the same variable (number). inputTensor dimensions: 140x7 - 140 arrays of size 7 inputMinArray dimensions: 1x7 - ...

Changing the Class of an Element in a Different Component with Angular 2+

Currently in a project utilizing Angular 4, I have implemented two components: app.component and other.component Within app.component.html, there exists a div with the name attribute myClass. <div class="myClass"></div> In the other.componen ...

Ways to display the ChaptersButton in Videojs-Player

I'm trying to incorporate videojs (version 8.10.0) into my project and provide viewers with a way to select chapters within the video. According to the official documentation, it seems that simply including a track element linking to a VTT file within ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

What could be causing the Ioncol not triggering the Onclick event?

I am facing an issue where my onclick event is not working on an ion-col. The error message says that the method I call "is not defined at html element.onclick". Here is a snippet of my code: <ion-row style="width:100%; height:6%; border: 1px solid # ...

Unexpectedly, the Discord bot abruptly disconnects without any apparent cause

Hey there! I've encountered an issue with my Discord bot - it keeps disconnecting after a few hours without any apparent cause! This particular bot is designed to regularly ping the Apex Legends game servers to check their status and display the ser ...

Calculator: Show individual digits once more following a calculation

After clicking the 'equal' button, the result is displayed. However, if I click another number, it doesn't clear the result. I want the result to stay when operation symbols like '+' or '/' are pressed. While working on t ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Angular 10 not triggering function on sortable update

activateSort(){ /* let isLoadedInCard = false; */ $(".group-items" ).sortable({ containment: "document", opacity: 0.6, scroll: true, items: ".group-item", placeholder: "item-pl ...