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

When <li> elements are rendered via ajax, it is not possible to attach JavaScript Events to them

Hey there, I've got a drop down menu that's being shown using UL and LI tags. This is generated by a PHP script that echos out: '<li id='. $value .'>'.$value.'</li>' The JQuery function below works perf ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

Is there a way to duplicate an image a specified number of times depending on a given output value?

As a beginner in coding, I am looking to learn how to dynamically insert multiple images based on input and output values. Currently, my code for basic addition looks like this: <form oninput="x.value=parseInt(a.value)+parseInt(b.value)"> <inpu ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Adjust the content size to 100% based on the quantity of items in a row

I've been having a hard time creating an image gallery that adjusts its size automatically (width: 100%) based on the number of items it contains. For example, take a look at this gallery: http://codepen.io/anon/pen/eNMOEz .item { width: 75px; h ...

Angular 2 - Module 'ng-factory' not found

I am encountering an issue when trying to launch my clean UI theme using 'ng serve'. This is my first time working with Angular and I'm struggling to resolve this problem. Any assistance would be greatly appreciated. I have attempted re-inst ...

Angularjs's approach to managing HTTP connections through connection pooling

In the process of generating numerous requests from my angularjs application to a backend REST server, I am utilizing the http service to initiate calls. My objective is to manage the concurrency of requests sent to the server as I am aware that the browse ...

How to implement a scrollbar for tables using Angular

How can I implement a vertical scroll bar only for the table body in my Angular code? I want the scroll bar to exclude the header rows. Since all rows are generated by ng-repeat, I am unsure how to add overflow style specifically for the table body. Here ...

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

The login controller fails to retrieve any values upon submission

My current controller setup looks like this: var myApp = angular.module('myApp', ['ui.router']); myApp.controller('loginController',['$http', function($http) { this.loginForm = function(){ console.log(th ...

Incorporating TypeScript into a project originally developed in JavaScript

I'm considering using TypeScript to write code for a JavaScript project. I've come to appreciate the benefits of TypeScript and am especially interested in using it for our AngularJS 1.5 project, which we plan to migrate soon. As I'm new to ...

Tips for loading JSON data into the select2 plugin

My goal is to extract the last two letters (in this case "VA") from the data attribute (data-code="US-VA") of a jvectormap-element using JVectormap. I want to compare these letters with State objects in the database and then load corresponding counties in ...

Issue with Bootstrap error class not functioning in conjunction with hide class

I need to create a form that slides down two input fields when an error occurs, and I want them to have the bootstrap error class. The 'error' class works fine without the 'hide' class being present, but when the 'hide' class ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...

Link that causes the regular expression test to hang

My goal is to create a regular expression that can accurately identify URLs. I found the code snippet for this on Check if a Javascript string is a url. The code looks like this: function ValidURL(str) { var pattern = new RegExp('^(https?:\/&b ...

Creating an Angular project that functions as a library and integrating it into a JavaScript project: a step-by-step guide

Is it feasible to create an Angular library and integrate it into a JavaScript project in a similar manner as depicted in the image below? The project structure shows trading-vue.min.js being used as an Angular library. Can this be done this way or is th ...

What is the process of calculating the difference between two time values in PHP?

I have searched everywhere online and tried multiple methods over the past couple of days, but still can't seem to achieve the desired result. My goal is to subtract two different times, for example 22:00:00 - 00:30:00 = 21:30:00 $hourToEatLastMeal = ...

Convert the user input into a div by clicking a button

Here is the code snippet I am currently using: $(document).on('click', '#editDetailBtn', function () { var input = $('<input id="#detailprimaryDescription" type="text" />'); input.val($('#detailprimaryDes ...

Using Flexbox CSS to Expand a Box According to its Content Size, Without Impacting Adjacent Rows

Is there a way to make the bottom-most row (highlighted in yellow) expand downward to fill available space? Check out this link for reference: https://jsfiddle.net/darrengates/oucvnfke/ I initially thought using: flex: auto; would solve the issue. Whil ...

Ways to establish a minimum height for material cards using Material UI

I am facing an issue with a card that contains a nested table. The card expands and shrinks based on the size of the table inside it. I want to prevent the card from shrinking when the table has no data or just one entry. Instead, I need the card to mainta ...