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

Experience the magic of Materialize CSS SideNav

I'm currently attempting to implement the mobile side navigation provided by Materialize. I've managed to display the menu icon, but when I click on it, nothing happens. It seems like the function is not being triggered, and there are no errors s ...

Guide to dynamically loading customer data into an HTML table using JavaScript

I'm looking to populate a table with data on customers including their name, customer ID, and rental cost. Can anyone help me with the JavaScript code needed to insert this data into rows of the table? Your assistance is greatly appreciated. Below is ...

Mastering the art of invoking a JavaScript function from a GridView Selected Index Changed event

In my current setup where I have a User Control within an Aspx Page and using Master Page, there's a GridView in the User Control. My goal is to trigger a javascript function when the "Select" linkbutton on the Gridview is clicked. Initially, I succe ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Establish a React component to observe socket.io

I am currently looking for the best way to connect my React component with socket.io in order to listen to events. My current approach involves including the following HTML code: <script src="socket.io/socket.io.js"></script> and then initial ...

Converting JSON data from an API file into a CSV format

Currently, I am working on converting the JSON output received from an API request into a CSV format for storage in our database. Below is the code snippet I am using for reference: // Python code here... Sample data obtained from the API: // Sample API ...

Accessing a specific data point from a Rest Api with React JS

How can I extract the value '00000000000000000000000000000000' that comes after clusters in the links->href in a Rest Api response? [{ "analysisUnits": [ { "links": [ { "href": "http://127.0. ...

What is the best way to determine the position of a letter within a string? (Using Python, JavaScript, Ruby, PHP, etc...)

Although I am familiar with: alphabet = 'abcdefghijklmnopqrstuvwxyz' print alphabet[0] # outputs a print alphabet[25] #outputs z I am curious about the reverse, for instance: alphabet = 'abcdefghijklmnopqrstuvwxyz' 's' = al ...

The Ladda spin animation continues spinning for an additional second after the stop() function is called

I employ the ladda spinner in this manner: var l = Ladda.create(document.getElementById('ladda-test')); l.start(); l.stop(); console.log('ladda is stoped'); The issue I am facing is that following the execution of l.stop(), the animat ...

Leverage and repurpose OOP objects

I am exploring how to inherit from Button using prototypes. Despite my efforts, the alerted name remains "Sarah" as it is the last Child created. I believe the Creator Class should be responsible for setting the name using a Method in Button. Check out m ...

Is it possible to modify the HTML/CSS of a child component using the parent component in Angular 2+?

Is there a way to dynamically add text and style to a specific row in a child component based on the parent's logic? (parent): <body> <child-component></child-component> </body> (child): <div *ngfor = "let record in r ...

Errors in Data Capture from AJAX Dropdown Selections

Recently, I've encountered an issue with one of my data fields while attempting to save it to a mySQL database. The problem seems to be related to the fact that the 'id' for the text value is saved instead of the actual text value itself, wh ...

Constantly encountering crashes with Swifty JSON

Utilizing SwiftyJSON for parsing json responses from the server. Encountering frequent app crashes (reports in crashlytics) but unable to pinpoint the exact location. All reports point towards this line of code: let jsonDict = JSON(data: data, options: ...

Modifying Parent Component Layout Using Vue.js

I am currently in the process of converting a UI element into a component for the purpose of reuse. This particular element consists of two buttons that toggle the visibility of two DOM elements within the parent app. The state of these buttons is stored i ...

Employing the JSON return code

I am attempting to implement ajax with php. Here is the PHP script I have: <?php // This file retrieves the POST information sent by an AJAX request and returns the values if successful. $price['name'] = "Called"; $price['Wheel'] ...

Converting JSON Data to DataFrame in Scala with Nested Structures

Currently, I am utilizing Spark/Scala to execute an API Request and then parse the response into a dataframe. For testing purposes, I have included a sample JSON response which can be found here. While attempting to convert the JSON string to a dataframe ...

Unable to transform into a tangible entity

When I run the code below, I encountered an error stating: Uncaught exception: TypeError: Cannot convert 'validation.messages.field' to object $.fn.validate = function(validation) { $.each(validation.rules, function(field, fieldRules){ ...

Obtaining a cookie in Vue.js independently: a step-by-step guide

After setting a cookie using laravel, I'm looking to retrieve it in vue.js without relying on or installing any external dependencies. Can anyone please suggest a way to achieve this without extra tools? Your guidance would be greatly appreciated! ...

Why isn't my List<string> being retrieved from the MVC Controller in an $ajax request?

I am attempting to generate customized lists in my cshtml file through an ajax request. .ajax({ type: "GET", cache: false, url: "@Url.Action("getValidationLists")", contentType: "application/json", dataType: "json", ...

Challenge with Filter Functionality when Activating Button

Can you help me implement a search filter using buttons with the Isotope Plugin? For example, entering a search value in an input field and then clicking a search button to display the search results. How can I achieve this using buttons? Below is the H ...