After refreshing the page, the local storage does not appear

I've been struggling to get it working for hours with no luck. After submitting the form, I create local storage values for name, surname, and email so that they can be automatically filled in the form next time without requiring the user to retype them. The submit() function is located in review.controller.js.

(function () { 'use strict';

angular.module('app').controller('ReviewController', ReviewController);

ReviewController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$route','$cookies','localStorageService'];
function ReviewController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$route,$cookies,localStorageService) {
   var vm = this;
    vm.name = null;
    vm.surname = null;
    vm.Email = null;
    vm.review = null;
    vm.allgenres = [];
    vm.submit = submit;
    vm.allreviews = [];
    $scope.localArray=[];
    loadAllReviews();
    submit();

    $scope.templates = [{ name: 'man.main.view.html', url: 'main/main.view.html'}];
    $scope.template = $scope.templates[0];

    function loadAllReviews() {      
        UniversalService.GetAllReviews()
            .then(function (review) {
                vm.allreviews = review;                    
            });
    }

    $scope.init = function () {debugger;
       // $scope.$MainController.obtained_array = localStorage.getItem("storageKey");debugger;
        $scope.storageKey = localStorage.getItem("storageKey");debugger;
    };

    $scope.storageKey = localStorage.getItem('storageKey');

  /*  $scope.$watch("storageKey", function() {debugger;
        localStorage.setItem('storageKey', storageKey); 
    });*/


    function submit() {  
    if($rootScope.name!=null)    {
        var JSONObject = {
             "name":$rootScope.name,
             "surname":$rootScope.surname,
             "email":$rootScope.email,
             "review":$rootScope.review
            }
        var temp={
            "name":$rootScope.name,
             "surname":$rootScope.surname,
             "email":$rootScope.email
        }
        $scope.localArray.push(temp);

        localStorageService.set("storageKey", $scope.localArray);

        $scope.storageKey = localStorageService.get("storageKey"); 
       // $rootScope.obtained_array = localStorageService.get("storageKey"); debugger;

        console.log($scope.storageKey);debugger;

        var Results = UniversalService.PostReview(JSON.stringify(JSONObject));
        }
    }
}

main.controller.js

'use strict';

var app= angular.module('app').controller('MainController', MainController);

MainController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$log','PagerService','localStorageService','$mdDialog'];
function MainController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$log,PagerService,localStorageService,$mdDialog) {
   var vm = this;
    vm.allreviews = [];
    vm.allusers=[];
    vm.allemails=[];
    vm.all=[];
    vm.avatars=[];
    $scope.filteredAll = [];
    $scope.all=[];
    $scope.items=[];

    $scope.pager = {};
    $scope.setPage = setPage;

    loadAllReviews();
    loadAllEmails();
    loadAllUsers();
    loadAll();
    loadAvatars();
    initController();
    setPage();
    submit();

    $scope.init = function () {
        $scope.$parent.storageKey = localStorage.getItem("storageKey");debugger;
       // $scope.obtained_array = localStorage.getItem("storageKey");
       // console.log(obtained_array); debugger;
       // $scope.storageKey = localStorage.getItem("storageKey");debugger;
    };


    function refresh() {
        location.reload();debugger;
    }


    function loadAll() {
        UniversalService.GetAll()
            .then(function (a) {
                $scope.all=a;
            });
    }

     function loadAllUsers(callback) {      
        UniversalService.GetAll()
            .then(function (response) {
                $scope.users=response;
                if (callback) {
                    callback(response);
                }
            });
    }

    function loadAllReviews() {      
        UniversalService.GetAllReviews()
            .then(function (review) {
                vm.allreviews = review;
            });
    }

    function loadAllEmails() {      
        UniversalService.GetAllEmails()
            .then(function (email) {
                vm.allemails = email;
            });
    }

    function setPage(page) {
        loadAllUsers(function (response) {
            if (response) {
                if (page < 1 || page > $scope.pager.totalPages) {
                    return;
            }
            // get pager object from service
            $scope.everything=response;
            $scope.pager = PagerService.GetPager(response.length, page);
            // get current page of items
            $scope.items = response.slice($scope.pager.startIndex, $scope.pager.endIndex + 1); 
            } 
        });
    }



    function initController() {
        $scope.setPage(1);  // initialize to page 1
    }

}

HTML file:

<div class="container padding-tb" id="Review">
<div ng-controller="ReviewController" ng-init="init()" ng-app id="Review">

<h2>Add review</h2>
    <form name="form" ng-submit="vm.submit()" role="form">
        <div >
            <div>
                <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" name="text" ng-model="name" onchange="CallItems()" id="name" class="form-control" ng-model="vm.name" placeholder="Enter name here"  required />
                    <span ng-show="form.name.$dirty && form.name.$error.required" class="help-block">Name is required</span>
                </div>
            </div>

            <div>
                <div class="form-group">
                    <label for="surname">Surname</label>
                    <input type="text" ng-model="surname" name="text" id="surname" class="form-control" ng-model="vm.surname" placeholder="Enter surname here"  required/>
                    <span ng-show="form.surname.$dirty && form.surname.$error.required" class="help-block">Surname is required</span>
                </div>
            </div>

             <div>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="text" name="email" id="email" class="form-control" ng-model="vm.email" placeholder="Enter email here" required />
                    <span ng-show="form.email.$dirty && form.email.$error.required" class="help-block">Email is required</span>
                </div>
            </div>

            <div>
                <div class="form-group">
                    <label for="review">Review</label>
                    <input type="text" name="text" id="review" class="form-control" ng-model="vm.review" placeholder="Enter review here"  required/>
                    <span ng-show="form.review.$dirty && form.review.$error.required" class="help-block">Review is required</span>
                </div>
            </div>

           <div class="form-actions">
                <button id="submit" type="submit" onclick="passInfo()" class="btn btn-primary">Submit</button>

                <label style="display:none" id="label"><font color="white">Review succesfully created!  

                <a onclick="refresh()" href="../ang/#!/review">Add new review</a></label> or 
                <a href="../ang/#!/">View reviews!</a>


            </div>
        </div>

    </form>

    <div>

        <div ng-init="init()" class="slide-animate-container">
        <div class="slide-animate" ng-include="main.view.html"></div>
        </div>
    </div>
</div>

Currently I add these values to button to test if values are added:

<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>

My main.view is inserted into the review.view (because form and reviews are on the same page, main is for the review listing and reviews are submitted form)

After submiting form all these values appear in the button, but after refreshing page none of them are shown anymore. I kind of understand that it is all because everything I do with local storage is inside submit() function, but I am not sure how to fix it

Answer №1

To ensure persistent data storage, consider implementing an init function within the second controller to store values in local storage. By doing so, the stored value will be easily accessible every time you reload the page.

Answer №2

Take a look at the line below:

<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>

The variable "obtained_array" belongs to $rootScope, therefore it cannot be directly bound to the template.

A quick fix is to modify the following line for MainController

$scope.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;

for ReviewController (where you are setting "LS_wimmtkey")

$scope.$parent.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;

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

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

Tips for Passing Data Using Ajax Function in JavaScript

I've been working on creating an AJAX favorite button in PHP that behaves similar to Instagram and Twitter. Everything seems to be in order with my code, and I've attempted to make it work using the following steps: PHP Code: $user_id = $_SESSI ...

Exploring the concept of data model inheritance in Angular 2

In my Angular2 and ASP.NET Core project, I have set up the following: My C# .NET Core API returns the following classes: public class fighter { public int id { get; set; } public string name { get; set; } public datetime birthdate { get; set; } p ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

One can activate an event once all templates and data have been fully loaded

Is there a way to trigger an event once all templates and data have finished loading in an AngularJS application? I've completed my app, but on the production server there seems to be a delay where the templates load first and then the data follow, le ...

Determine if a certain value is present in an array within an HTML document

In the context of AngularJS, I have an array that looks like this: var test=["abc/1/1","def/2/2","efg/3/3"]; I am trying to determine if the array contains a value with "abc" in it within my HTML code. When I used the following: test.indexOf("abc")!=-1 ...

Tips for customizing the color of the current date in the angular-material datepicker

I've created a function in angular-material to disable dates two days from now, but I'm struggling to change the color of the current date if it's disabled. The issue is that when the current date is disabled, it displays in a very light blu ...

What is the best way to utilize the useSWR hook when there are necessary logical operations to be performed on the response before proceeding with the next API call

I am currently utilizing the swr library in a Create React App and require the usage of the useSWR hook for data fetching that is both contingent and conditional. The specific task at hand involves: Making an API call to retrieve an id which will be used ...

Can't access innerText in Firefox

This is the code snippet I'm having trouble with: <div id="code">My program<br />It is here!</div> <script type="text/javascript"> var program=document.getElementById('code'); ShowLMCButton(program.innerText); </s ...

Sorting the array in MongoDB before slicing it

Currently, I have a pipeline that aggregates Regions along with their respective countries and sales values. My goal is to obtain the top 5 countries by sales in each region using the $slice method. However, the issue I am facing is that it returns the fir ...

Which one should I use: ng-repeat or ng-options?

I am looking to display JSON data in a dropdown list, and I have two options to choose from. The first option is using ng-repeat, while the other option is ng-options. Using ng-repeat: In the HTML file: <select> <option ng-repeat="prod in testA ...

Selenium Python not generating event when clicking on element (Key event missing from datafile)

One issue I am facing is that clicking on a button element does not trigger the event. Specifically, while attempting to add an item to the cart, a size must be selected before clicking the "add to cart" button. This problem occurs when using the Chrome he ...

"Addressing the issue of ineffective form validation for empty or whitespace inputs

I've been working on creating a form and everything seems to be going well except for the validation aspect. It doesn't highlight when intentionally left blank or filled with spaces. I have included "required" in the HTML which partially achieves ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

Using React to map through a nested array within an object

In an attempt to extract the nested array "records", my current approach shows the array in the react console, but with an error. I will try to be brief while still providing necessary details. Upon encountering an error, there are 3 lines specifically po ...

Managing URL patterns in AngularJS ui.router: Tips and Tricks

When utilizing the "ui.router" angular JS module, does this mean that the module will have complete control over all URL navigation on the entire page? Currently, I am using the $stateProvider.state method to define URL and State mappings. However, it see ...

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...

Ways to identify whether a div is in view and includes an input field

This is a unique question that is not related to the issue of querySelectorAll detecting value in input. Instead of asking whether an input field has a value, I am interested in how to detect if the current visible div contains an input field. This is a n ...

Reactjs - There was an error: $node.attr(...).tooltip is not defined

I am currently troubleshooting the SummerNote mention library and encountering an issue - Uncaught TypeError: $node.attr(...).tooltip is not a function The versions I am using are: - "react-summernote": "^2.0.0", - React version: "react": "^16.8.6", ...