Tips for incorporating local storage into Angular applications

After successfully creating a table using Angular, I decided to incorporate a local storage feature. Despite my efforts, I'm struggling with implementing gsklee/ngStorage and gregory/angular-local-storage libraries into my existing code.

Could someone please lend a hand? Thank you in advance for your time.

script.js

(function() {
"use strict";

 var table = angular.module('myTable', ['angularUtils.directives.dirPagination','ngStorage']); 

table.filter('startFrom', function() {
    return function(input, start) {
        if(input) {
            start = +start;
        return input.slice(start);
        }
        return [];
    }
});

    table.controller('TodoCtrl', function($scope, $http, $localStorage) {
    $http.get('todos.json').then(function(res) {
        $scope.todos = res.data;
    });

    $scope.currentPage = 1; 
    $scope.entryLimit = 5;

    $scope.sort = function (keyname) {
        $scope.sortKey = keyname;
        $scope.reverse = !$scope.reverse;
    };  

    $scope.DeveloperDelete = function (id){
        var result = confirm('Are you sure?');
        if (result === true) {  
            var index = getSelectedIndex(id);
            $scope.todos.splice(index, 1);
        };
    };

    function getSelectedIndex(id){
        for(var i = 0; i < $scope.todos.length; i++)
            if($scope.todos[i].id == id)
                return i;
            return -1;  
    };

    $scope.addDeveloperRow = function(){        
        $scope.todos.push({ 'id':$scope.id, 'text': $scope.text, 'color':$scope.color, "progress:":$scope.progress});
        $scope.id='';
        $scope.text='';
        $scope.color='';
        $scope.progress='';
    };  

}); 


})();

index.html

<!doctype html>
<html ng-app="myTable" >
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<script src="dirPagination.js"></script>
<script src="ngStorage.js"></script>

... (omitted for brevity)

 

Answer №1

Check out this example I created for managing local storage without the need for any third-party libraries. It's a simple solution that can easily be implemented.

(function() {
    'use strict';
    angular.module('myApp')
        .service('LocalStorageService', [
            '$window', function($window) {
                var service = {
                    store: store,
                    retrieve: retrieve,
                    clear: clear,
                    clearAll: clearAll
                };

                return service;

                function store(key, value) {
                    $window.localStorage.setItem(key, angular.toJson(value, false));
                }

                function retrieve(key) {
                    return $window.localStorage.getItem(key);
                    // return angular.fromJson($window.localStorage.getItem(key));
                    // Need to deserialize the stored JSON data before using it
                }

                function clear(key) {
                    $window.localStorage.removeItem(key);
                }


                function clearAll() {
                    $window.localStorage.clear();
                }


            }
        ]);
})();

To use this, simply inject it into your controller and start using it.

For example:

table.controller('TodoCtrl', function($scope, $http, LocalStorageService) {
    $scope.todos = LocalStorageService.retrieve('todos');
    if (!$scope.todos){    // If 'todos' is not stored yet, $scope.todos will be null
        $http.get('todos.json').then(function(res) {
            $scope.todos = res.data;
            LocalStorageService.store('todos', $scope.todos);
        });
    }

}

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

After executing webpack, it has been noticed that one of the dist files consistently ends up empty

As someone who is new to webpack, I have successfully used the quick start guide to process a simple JS file from src to dist. Everything was working fine. However, I encountered an issue when trying to process more than one JS file. The original tutorial ...

Having issues with ASP.NET MVC AJAX PartialView not loading Telerik UI components

I am facing an issue with a PartialView that I update using AJAX. The HTML elements load correctly when updating the Div with AJAX, but the Telerik chart is not loading. The datasource in the chart does not call the Action method: .DataSource(ds => ds. ...

Creating a form in NextJS to securely transfer user input data to MongoDB

Being new to JavaScript, I have a basic understanding and some lack of experience, but I am eager to learn more. Recently, I embarked on a project using NextJS, an efficient framework that integrates with ReactJS. My current challenge lies in creating a si ...

Finding the source of the err.kind expression in the MERN stack: Unraveling the mystery

Recently, I've been delving into the world of MERN stack development and came across an interesting technique for Error Handling in a tutorial. The tutorial showcased various expressions that can be used to identify different types of errors being thr ...

Iterate over an array utilizing the $.getJSON method for data retrieval

I have encountered an issue while using a for loop to iterate through an array of dates in a JSON request. The problem is that the loop seems to be fetching only the first item in the array each time it iterates, as if ignoring the variable i or being cach ...

npm ERROR: Unable to install the package named "<packageName>" because it conflicts with an existing package of the same name

Currently, I am attempting to incorporate the jsonfile package into my project. However, I am encountering a couple of errors: An issue arises when attempting to install a package with the same name as another package within the same directory. (Despite ...

Finding the current week using date information from an array of objects in JavaScript

I have an array of objects with a date key, and I am trying to filter out the objects that fall within the current week. How can I achieve this and get the objects from the current week? I attempted to use the filter method, but I believe I need to forma ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

The ngMessagesInclude directive is not functioning properly within the ngMessages directive

What's Included: angular/angular.min.js angular-route/angular-route.min.js angular-messages/angular-messages.min.js This module belongs to me. var myModule = angular.module('myModule', [ 'ngRoute', 'ngMessages' ...

Removing undesired entries from a table view using AngularJs

In my table, there is a column called status which could have values like 'Open', 'Closed', 'Verified' and 'Rejected'. I am looking for a way to implement a filter in ng-repeat that will hide the rows with the statu ...

Having trouble persisting and displaying information in MongoDB with Mongoose

app.post('/contact', (req, res)=> { var myData = new Contact(req.body); myData.save().then(()=>{ res.send("Item has been saved"); }).catch(()=>{ res.send('Item was not saved due to some error'); ...

Tips for Preserving the HTML Page State After Making jQuery Changes

Hi there! I am currently working on developing a card game using HTML5, CSS3, and Javascript. This game will communicate with a server built on node.js, facilitated by socket.io for data transmission. One of the key features I am trying to implement is th ...

Discover the magic of TransformToggle and slideToggle in Javascript, HTML, and CSS

Working on a website coding project and ran into an issue. Trying to utilize an img as a link to slideToggle content. It's working, but I'd like the img to rotate 90deg on the first click and -90deg on the second one. Any solutions are greatly ap ...

Conceal the loading spinner in JQuery once the image has finished loading

I am working with a jQuery function that captures the URL of an image link and displays the image. However, my issue lies in managing the loading process. I would like to display a LOADING message and hide it once the image has fully loaded, but I am strug ...

What is the best way to showcase an item from an array using a timer?

I'm currently working on a music app and I have a specific requirement to showcase content from an array object based on a start and duration time. Here's a sample of the data structure: [ { id: 1, content: 'hello how are you', start: 0 ...

The functionality of form.serialize() seems to be malfunctioning

I encountered an issue with my webpage called "View Employee." When we click on it, all the employees are displayed with an edit button for each one. Below is the corresponding page: echo "<form class="form-horizontal id="update_form" name="update_form ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

How can Angular be used to fetch the name associated with a user_id in Laravel?

There seems to be a problem with fetching the name attribute along with the title and body attributes. The name appears empty on page refresh but shows up automatically upon submission. Interestingly, angularjs is unable to retrieve the name successfully. ...

The property cannot be set because it is undefined in nodejs

var list = [ { title : '', author : '', content : '', } ] router.get('/japan',function(req,res){ var sql = 'select * from japan'; conn.query(sql,function(err,rows,fields){ for(var i = 0 ; ...

Enhance Your Angular SPAs with Automated Accessibility Testing Tools

Has anyone had success using an automated accessibility testing tool specifically designed for Angular Single Page Applications (SPA)? I experimented with pa11y, but it was not providing consistent results. I'm curious if there are other tools simila ...