What would be the most efficient method in Angular for saving and retrieving information on whether a user has previously selected a checkbox?

I am currently in the process of learning angular as I develop a web application that resembles a todo list, specifically focused on football teams. In this application, users can navigate through a menu to select a league from four options. The application then retrieves data based on the league selected and displays a list of teams with checkboxes. Users can check off the football grounds they have visited during the season.

While the functionality works smoothly, I am looking for guidance on how to store user selections using localStorage and retrieve them upon page load.

Initially, I attempted to use the ng-change() method but encountered issues with displaying the correct data for each league due to retrieving the same data from localStorage instead of the JSON file corresponding to the ID. Any advice or assistance on resolving this would be highly appreciated!

Below is the HTML markup containing the teams and checkboxes:

<ul class="list-unstyled">
  <li ng-repeat="club in league" ng-click="selectClub(club.id)">
    <input type="checkbox" ng-model="club.done">
    <a href="#/team">{{club.club}} - {{club.ground}}</a>
  </li>
</ul>

Here is the controller code responsible for fetching the league ID and loading the data:

trackerControllers.controller('ClubCtrl',  ['$scope', '$http', function($scope, $http) {
    var leagueId=sessionStorage.getItem("leagueId");
    $http.get('JSON/Leagues/league'+leagueId+'.json').success(function(data) {
        $scope.league = data;
    });
}]);

If there are any suggestions to improve the clarity of my question, please feel free to provide them. Thank you!

To better visualize the site, here is the link to the new version:

For reference, here is the link to the old version where data was stored differently:

Answer №1

Monitor changes in the checkbox for each club and update localStorage whenever there is a change.

<ul class="list-unstyled">
  <li ng-repeat="club in league" ng-click="selectClub(club.id)">
    <input type="checkbox" ng-model="club.done" ng-change="updateClub(club)">
    <a href="#/team">{{club.club}} - {{club.ground}}</a>
  </li>
</ul>

$scope.updateClub = function (club) {
    var key = 'clubId-' + club.id;
    if (club.done) {
        localStorage.setItem(key, 'viewed');
    } else {
        localStorage.removeItem(key);
    }
};

When fetching data, verify if each club has been viewed previously.

trackerControllers.controller('ClubCtrl',  ['$scope', '$http', function($scope, $http) {
    var leagueId=sessionStorage.getItem("leagueId");
    $http.get('JSON/Leagues/league'+leagueId+'.json').success(function(data) {
        var i;
        for (i = 0; i < data.length; i++) {
            // check if this team has been viewed
            data[i].done = localStorage.getItem('clubId-' + data[i].id) === 'viewed';
        }
        $scope.league = data;
    });
}]);

Answer №2

The program will take the identification number of the selection and load the following page by sending a request for a JSON file over HTTP.

One of the strengths of Angular is its ability to dynamically render different templates or views on the same URL, rather than loading separate pages like a traditional website would do. This eliminates the need to "pass" variables between pages, as you can simply store them within the scope.

For example, upon user interaction:

$scope.leagueId = 1;

Since the scope is accessible to the controller, you can easily retrieve the LeagueId value from it.

$http.get('JSON/Leagues/league' + $scope.leagueId + '.json').success(function(data) {
   $scope.league = data;
});

I recommend utilizing a database to store your data and implementing queries to retrieve specific information based on input parameters. It's also advisable to access the data from a service or factory instead of directly from the controller.


Update:

After reviewing the question again, it seems that you intend to persistently save user inputs. To achieve this, you'll require database storage and user authentication systems to identify users and track their actions.

Here's an ideal setup:

  • User table for storing user credentials (login)
  • Action table defining user-permissible actions
  • User-Action table recording which users have performed which actions

Using $scope won't suffice since it ends when the browser closes, session storage isn't reliable due to expiration, and cookies are limited to individual devices. Hence, a more robust solution involving databases and authentication mechanisms is necessary.

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

Creating a Wordpress Metabox that utilizes radio inputs generated with Javascript instead of the traditional checked() function in Javascript as an alternative

Despite my efforts to find a solution on various forums, I am still stuck with this issue without making any progress. The code snippet below contains two Radio inputs. These inputs are generated on the post edit page of Wordpress CMS and their values com ...

Unknown individual, yet revealed by the investigator

I'm attempting to develop a dynamic list in react.js generateList = () =>{ return this.state.user.map((u)=>{ console.log(u); return <li onClick={this.handleClick} id={u} name={u}>{u}</li>; }); } The hand ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

Spontaneous Link with JQuery and Colorbox

Just to clarify, I have no programming experience so please explain everything in simple terms. I am currently using a .js script within SharePoint and it's working perfectly! <!DOCTYPE html> <html> <head> <meta charset= ...

Is there a way to automatically collapse all the collapsible elements within the accordion when closing it?

I came across a similar topic on Stack Overflow about closing all children accordions when the parent accordion is closed, which seems to address my issue. Currently, I am using Bootstrap 4 and struggling to modify the code from the other topic to ensure ...

Tips for handling two distinct versions of a single field during JSON parsing

Working with a JSON rest api that has the capability of returning two different variations of the same field. An example response from the api is as follows: "result": { "value": { "error": "Invalid data" ...

Reasons for a service not receiving events

I had a piece of code that was functioning well within a controller. I decided to refactor it and move the functionality to a service. The code contained an event listener: $rootScope.$on( .....) Previously, this event was caught when it was in the contr ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...

Ways to effectively go through local storage using a loop

I'm currently working on enhancing my navbar by adding links based on searches made by users and their favorite selections. My goal is to avoid duplicate entries in the "past searched" section if the current search already exists in the list. I'm ...

Can you tell me the name of this particular file format?

I am in need of assistance parsing a certain file format that looks like the example below: "General" { "Description" = "Some Text" "Version" = "4" "ProjType" = "1" } "Configurations" { "Mice" { "BuildOutputs" = "BuildProject" "OutputFile" ...

Real-time webpage featuring dynamically updating text sourced from a file

After spending 5 hours attempting this on my own, I've decided to reach out for help. I am in need of creating a page that will automatically update itself and display the content of a file when it changes. For example, let's say we have a file ...

Troubles with setting up slash commands in discord.js v13

I am encountering an issue while trying to deploy a slash command. The error message DiscordAPIError[50035] is displayed, stating "Invalid Form Body guild_id[NUMBER_TYPE_COERCE]: Value \"undefined\" is not snowflake." const path = require('n ...

Executing a Shortcode Using a Button in Visual Composer for Wordpress

It should be easy to do this. I've got a great plugin with a modal newsletter signup form that offers various launch options, including manual launching with the following codes. https://i.stack.imgur.com/IGbsp.png My theme utilizes Visual Composer. ...

Jolt Shift for adding extracted information

I have recently started using Jolt Transform and I am looking to transform some EDI data. My goal is to retain the original data while adding a few extracted elements to simplify the downstream process. Here's an example: Input { "id": &q ...

Shift the sideways movement of the triangle symbol

I currently have a main menu in the header with links, accompanied by a moving triangle that changes position as the user hovers from one page to another. While I want to maintain the dynamic movement, I am seeking a smoother transition effect similar to w ...

Merge two arrays based on date and sort them using Angular.js/JavaScript

I am facing a challenge where I have two JSON arrays, each containing a field named date. My goal is to compare the two arrays and merge them into a single array. Check out the code snippet below: var firstArr=[{'name':'Ram','date ...

Inquiring about a particular key-value in a buffer variable in GoLang

Within my code, I have a variable buffer that holds a collection of key-value pairs in an array format like this: [{"Key":"area1", "Record": {"name":"belfast","type":"surburban","v ...

utilizing vuex store within a JavaScript document

Currently, I'm encountering an issue while attempting to access my store from a helper function file: import store from '../store' let auth = store.getters.config.urls.auth An error is being logged: Uncaught TypeError: Cannot read prop ...

The performance of Controller.Json method decreases when working with IQueryable objects

My MVC controller action returns JSON data and currently takes around 2 seconds to complete. I would like it to be faster, ideally under 1 second. After profiling the controller action, I discovered that the line containing the return of JSON is slow, ta ...