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

Click on the link in the listview to close the panel

I'm currently working on a jQuery mobile page that includes a panel with a listview. Each list item has a link with a data-rel="close" attribute, and I want the panel to close whenever a list item is clicked. It's important to note that I am als ...

This JavaScript function is designed to strip HTML elements from a given

"p" tags are disappearing after running the javascript, but they are needed for structuring purposes. Is there a way to retain the html tags in the hidden/secondary text block even after the javascript manipulation? function AddReadMore() { //This lim ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

How can I add a black-colored name and a red-colored star to the Placeholder Star as a required field?

I'm looking to customize the placeholder text in an input field. I want the main placeholder text to be in black and have a red star indicating it's a required field. However, my attempt to set the color of the star specifically to red using `::- ...

Having trouble with preventDefault() not working during a keyup event?

I am struggling to make preventDefault() function properly. Here are a few variations of the code that I have attempted: First: $(document).keyup(function (evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode == 192) { ...

What is the best way to pass a Python string to a JavaScript script?

I attempted to utilize the JSON module for this task, but encountered errors in both my JavaScript script and Firebug. For example, I have a line that looks like this: {"fruit":{"apple":100}} When trying to send this to a JavaScript script called jquery. ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

Unable to load AngularJS thumbnails from JSON file? Learn how to showcase a larger image by clicking on the thumbnail

Working with AngularJS to retrieve image data from a JSON file has been successful for me. My next task involves loading all of the thumbnail images into the gallery div and populating the src, alt, and title attributes using ng-repeat. However, this part ...

What is the method for accessing a selector within a foreach loop?

Whenever a user clicks on a date in the jquery datepicker, two ajax calls are triggered. The goal is for the second ajax call to populate the response/data into a paragraph with the class spots within the first ajax call, displaying available spots for th ...

Issue in d3.js: bisector consistently returning zero

http://jsfiddle.net/rdpt5e30/1/ const data = [ {'year': 2005, 'value': 771900}, {'year': 2006, 'value': 771500}, {'year': 2007, 'value': 770500}, {'year': 2008, 'value&apos ...

Adding elements to a two-dimensional array using AngularJS

How can I assign the value of an input to tasks.name and automatically set status: false when adding a new item to the $scope.tasks array? HTML <input type="text" ng-model="typeTask"> <button ng-click="updateTasks()">Add task</button> ...

The JavaScript counterpart to jQuery's click event handler

I'm trying to figure out how to achieve the same effect as this jQuery code. var divQuery = $('.html5gallery-thumbs-0').children(); divQuery.on('click', function () {...} I attempted it like this: var divQuery = document.g ...

Automatically navigate through form fields using jQuery when pasting data

Enhancing the form filling experience by allowing users to prepare a text file in advance and simply copy/paste it into the form for quick submission. Integration of a feature that automatically moves to the next input field when a tab or newline character ...

Using Vuetify to display text fields in a single row

Check out this Vue component template (View it on CODEPEN): <div class="some-class"> <v-form > <v-container @click="someMethod()"> <v-row> <v-col cols="3" sm="3" v-for="p in placeholders" ...

Explore the connection between video streaming with DynamoDB and AngularJS by checking out the

In my project, I have stored some videos in an S3 bucket and their references are saved in a DynamoDB table along with other relevant information. To display this data, I have developed an AngularJS application that fetches the items from the Dynamo table ...

How can I design an avatar image within a button similar to Facebook's style?

I'm currently working on a project that involves adding an avatar and a dropdown menu for account settings to my navigation bar. I've already created the dropdown, but I'm having trouble styling the avatar within the button. The button is ta ...

``The Art of Handling REST API with Express and Mongoose

Running Express on my application, I have a delete route set up as shown below: router.route('/lists/:id') .delete(function(req, res){ Entry.remove({ _id: req.params.id }, function(err, list){ if(err) ...

Does anyone know of a way to integrate a calendar feature into a React application using a library

Greetings to everyone, I trust you are all enjoying a fantastic day. I am in search of an interactive calendar similar to this one for one of my applications Does anyone know of a React library that could assist me in creating such a feature? ...

Exploring the World of Vue.js Object Imports

I am currently encountering an issue involving the importing of Objects from App.vue into a component. To provide context, this project consists of a Navigation Drawer component and an App.vue file. The Navigation Drawer contains Vue props that can be dyna ...

If you press Ctrl + F, the browser will disable the form search function

How can I prevent the form find browser functionality when pressing Ctrl+F, and instead focus on the element html? <div id='demo'> <form class="id5-text-find-form" id="id5-text-find-form"> <input class="search" placeho ...