managing, modifying and removing information within the app.controller in AngularJS

I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on:

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

app.controller('MainCtrl', ['$scope', 'filterFilter', function ($scope, filterFilter) {
    $scope.items = ["name 1", "name 2", "name 3"
    ];

    $scope.addLink = function () {
        $scope.errortext = "";
        if (!$scope.newItem) {return;}
        if ($scope.items.indexOf($scope.newItem) == -1) {
            $scope.items.push($scope.newItem);
            $scope.errortext = "submitted";
        } else {
            $scope.errortext = " in list";
        }
    };

I have set up the above code and it works fine on the frontend where users can add and delete items from the list. However, I am looking for a solution to ensure that any changes made by the user are persisted even after reloading the page. Does anyone have suggestions on how to achieve this? Would storing data in cookies be a viable option, and if so, how can it be implemented?

Thanks!

UPDATE: I made some modifications to the script but it still doesn't seem to work as intended.

var app = angular.module('App', ['ui.bootstrap']);

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

app.factory('ItemsService', ['$window', function ($window) {
    var storageKey = 'items',
        _sessionStorage = $window.sessionStorage;
    return {
        getItems: function () {
            var itemsStr = _sessionStorage.getItem(storageKey);

            if (itemsStr) {
                return angular.fromJson(itemsStr);
            }
        },
        putItem: function (item) {
            var itemsStr = _sessionStorage.getItem(storageKey),
                items = [];

            if (itemStr) {
                items = angular.fromJson(itemsStr);
            }

            items.push(item);

            _sessionStorage.setItem(storageKey, angular.toJson(items));
        }
    }
}]);

app.controller('MainCtrl', ['$scope', 'filterFilter', 'ItemsService', function ($scope, filterFilter, ItemsService) {
    $scope.items = ItemsService.get($scope.items)

    $scope.addLink = function () {
        $scope.errortext = "";
        if (!$scope.newItem) {
            return;
        }
        if ($scope.items.indexOf($scope.newItem) == -1) {
            $scope.items.push($scope.newItem);
            $scope.errortext = "Submitted";
            $scope.items = ItemsService.put($scope.items)
        } else {
            $scope.errortext = "Link in the list";
        }
    };

    $scope.removeItem = function (item) {
        $scope.items.splice($scope.items.indexOf(item), 1);
        $scope.items = ItemsService.put($scope.items)
        $scope.resetFilters;
    };
}];

Any suggestions on how to fix this issue and ensure that if a user has no items, it defaults to $scope.items = ["name 1", "name 2", "name 3"]; ?

Answer №1

To simplify the interaction with cookies, consider creating a get/set service utilizing the $cookies module. Here's an example implementation:

angular.module('myApp')
  .factory('ItemsService', ['$cookies', function($cookies) {
    var cookieName = 'items';
    return {
      get: function(defaults) {
        return $cookies.get(cookieName).split(',') || defaults;
      },
      put: function(items) {
        var expireDate = new Date();
        expireDate.setDate(expireDate.getDate() + 1);
        $cookies.put(cookieName, items.join(','), { expires: expireDate });
      }
    };
}]);

Don't forget to include ItemsService in your controller and within the main function:

$scope.items = ItemsService.get($scope.items);

This will retrieve the updated list stored in $cookies (if any). To save the list, use the addLink() function as follows:

ItemsService.put($scope.items);

Answer №2

I want to enhance @davidkonrad's solution by suggesting the use of sessionStorage in his service. sessionStorage is the most suitable option for your particular use case.

angular.module('myApp')
  .factory('ItemsService', ['$window', function($window) {
     var storageKey = 'items',
        _sessionStorage = $window.sessionStorage;

     return {
        // Retrieves stored items array if available, or returns undefined
        getItems: function() {
            var itemsStr = _sessionStorage.getItem(storageKey);

            if(itemsStr) {
                return angular.fromJson(itemsStr);
            }         

            return ['name1', 'name2', 'name3']; // default value when nothing is stored in sessionStore                
        },
        // Adds the provided item to the stored array and saves the array to sessionStorage
        putItem: function(item) {
            var itemsStr = _sessionStorage.getItem(storageKey),
            items = [];

            if(itemStr) {
                items = angular.fromJson(itemsStr);
            }

            items.push(item);

            _sessionStorage.setItem(storageKey, angular.toJson(items));
        }
     }
}]);

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

What is the method used by Vue.js to establish observers in computed properties?

Consider this scenario: computed: { greeting() { const state = this.$store.state; if (state.name === 'Joe') { return 'Hey, Joe'; } else { return 'Hello, ' + state.name; } } } Which object(s) w ...

A collection of jQuery objects that consist of various DOM elements as their properties

Seeking a more concise and potentially more streamlined approach using jQuery. I have an object called lbl which represents a div. Inside this div, there is a span tag that contains the properties firstName and lastName of the lbl object. Here's how t ...

Leveraging the power of JavaScript Math methods to dictate the Co-ordinates of HTML Canvas .fillRect

Greetings to everyone! I have dedicated my entire evening to understanding how to implement the (Math.floor(Math.random()) function as the coordinates for the .fillRect method on an HTML canvas element. Despite searching through this website and various ...

Adjust the color of each list item depending on an array of strings

Within my perspective, I possess a collection of different statuses. <ul> <li>FIRST_STATUS</li> <li>SECOND_STATUS</li> <li>THIRD_STATUS</li> </ul> To continuously update the statuses in my contr ...

Easily move elements using a jQuery click animation

Having trouble animating a div's top position by -130px to move it off screen? Can't figure out why it's not working? I'm fairly new to jQuery/Javascript. I have a button/hyperlink with the ID #NavShrink. When clicked, I want the div # ...

Python on the server side generating a downloadable zip file

After passing a parameter from my client to a python script on the server through a GET request, the script initiates a process that results in the creation of a zip file. However, upon making an AJAX call in my client-side JavaScript, I am only able to co ...

The error message encountered is: "TypeError: Unable to access the 'apply' property of an undefined object within the

Currently in the process of developing a node js application with the integration of DHTMLX Scheduler feature on one of the pages. However, my progress is hindered by a recurring issue upon loading the page, resulting in the following error message: TypeE ...

The drop-down does not move above the subsequent div when focused

I have implemented a dropdown feature on focus of an <input type='text'> box in the following manner http://jsfiddle.net/Newtt/7ffdF/ The issue I am facing is with the positioning of the dropdown box. It currently displaces the content of ...

The incorporation of zoom disrupts the smooth scrolling capability of the menu

My landing page has a menu that scrolls users to the selected section. However, my client prefers the page at a 90% zoom level. To accommodate this request, I added the following line of code: body { zoom:90%; } Unfortunately, when I click on a menu o ...

Remove any words that are not included in the specified list

Here is the code snippet to achieve the desired functionality: const { words } = require("../../json/words.json") const args = message.content.split(' ') const wordss = words.filter(m=> m.includes(args)) if(args > 1 || !wordss) { ...

Harnessing the power of custom directives in HTML

I have developed a custom directive that adds the active class to the clicked li element in the menu list based on the URL. .directive('addActive', [function() { return{ ... link : function(scope, element, attrs){ ...

List with pulldown options

I am trying to implement a drop-down list with bullets using Angular 2, JavaScript, and CSS. Although I have managed to create the drop-down list, I am facing difficulty in adding bullets to the list items. Unfortunately, I have found that jQuery and Boot ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

Tips for setting default values for named parameters in JavaScript

In my TypeScript method, I am using named parameters like this public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) { } The parameters m and n will be provided from another object like const defaults = { m : 'M&apo ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

Sorting Object Values with Alternate Order

Is there a way to sort a JSON response object array in a specific order, especially when dealing with non-English characters like Umlauts? object { item: 1, users: [ {name: "A", age: "23"}, {name: "B", age: "24"}, {name: "Ä", age: "27"} ] ...

What is the best way to retrieve the values of various input fields using their numbered IDs and then store them in a MySQL

I attempted to design a form that allows for multiple inserts, where users can add as many titles and languages as they desire by entering a number. The display of titles and languages is functioning correctly, but I am struggling to retrieve the individua ...

Exploring the art of path zooming in d3.js

Trying to resolve this issue, I adjusted the geoJsonURL to handle a more intricate shape. Despite the new shape allowing the zoom method to function correctly, the shape itself appears completely distorted. Based on the Coordinate system: WGS 84 (EPSG:4326 ...

The sidebar vanishes when you move your cursor over the text contained within

My issue is that the side menu keeps closing when I hover over the text inside it. The "About" text functions correctly, but the other three don't seem to work as intended. Despite trying various solutions, I am unable to identify the root cause of th ...