Updating class after refresh of ng-repeat in AngularJS/Javascript

I am currently using angularJs in conjunction with cordova.

Within my ng-repeat loop, each item has an ng-click event that stores the value of the item in an array. Additionally, when I click on an item, it toggles a class on the corresponding div (using the $index of ng-repeat), similar to a checklist.

The issue arises when I reload the ng-repeat, as the classes I added by clicking on the items are lost. I attempted to reapply these classes by calling a function that refreshes the items displayed in the ng-repeat, but unfortunately, the classes were not being added back.

Below is a snippet of my code :

<div id="ami" class="list-group">
           <div href="#" class="list-group-item" ng-repeat="ami in listeAmis"> {{ami.pseudo}}<i id="checkAmi{{$index}}" class="fa fa-circle-o pull-right" ng-click="mapCtrl.checkAmi(ami.pseudo, $index);"></i><i class="fa fa-user pull-left" ></i></div>
</div>

Javascript

var amisNotifies = [];

                mapCtrl.checkAmi = checkAmi;
                function checkAmi(pseudo, id) {
                    var info = ({
                        pseudo: pseudo,
                        id: id
                    });
                    var getIndexOf = function (psdu) {
                        for (var i = 0; i < amisNotifies.length; i++) {
                            if (amisNotifies[i].pseudo === psdu) {
                                return i;
                            }
                        }

                        return -1;
                    };

                    if (amisNotifies.length > 0) {
                        var index = getIndexOf(pseudo);
                        if (index > -1) {
                            // The item already exists, so remove it.
                            Array.prototype.splice.call(amisNotifies, index, 1);
                            $("#checkAmi" + id).addClass("fa-circle-o");
                            $("#checkAmi" + id).removeClass("fa-check-circle-o");
                        }
                        else {
                            // Item does not exist, add it.
                            amisNotifies.push(info);
                            $("#checkAmi" + id).removeClass("fa-circle-o");
                            $("#checkAmi" + id).addClass("fa-check-circle-o");
                        }

                    } else {
                        // The array is empty, so add the item.
                        amisNotifies.push(info);
                        $("#checkAmi" + id).removeClass("fa-circle-o");
                        $("#checkAmi" + id).addClass("fa-check-circle-o");
                    }
                    console.log(amisNotifies);
                }

Even after attempting to reapply the classes upon reloading the data shown by the ng-repeat, the classes remain unchanged...

if (amisNotifies.length > 0) {
            for (var i = 0; i < amisNotifies.length; i++) {
            console.log(amisNotifies[i].id);
            $("#checkAmi" + amisNotifies[i].id).removeClass("fa-circle-o");
            $("#checkAmi" + amisNotifies[i].id).addClass("fa-check-circle-o");
            }
}

Answer №1

Displaying HTML elements with dynamic ng-class stored in an array based on the index :

<div id="ami" class="list-group">
    <div href="#" class="list-group-item" ng-repeat="ami in listeAmis"> {{ami.pseudo}}
        <i id="checkAmi{{$index}}" ng-class="isChecked[{{$index}}]" ng-click="mapCtrl.checkAmi(ami.pseudo, $index);"></i>
    </div>
</div>

Defining variables based on the number of elements in the ng-repeat:

if ($scope.listeAmis.length > 0) {
    for (var j = 0; j < $scope.listeAmis.length; j++) {
        $scope.isChecked[j] = "fa fa-circle-o pull-right";
    }
}

Handling click events to toggle classes dynamically and updating the array accordingly:

mapCtrl.checkAmi = checkAmi;
function checkAmi(pseudo, id) {
    var info = ({
        pseudo: pseudo,
        id: id
    });
    
    var getIndexOf = function (psdu) {
        for (var i = 0; i < amisNotifies.length; i++) {
            if (amisNotifies[i].pseudo === psdu) {
                return i;
            }
        }

        return -1;
    };

    if (amisNotifies.length > 0) {
        var index = getIndexOf(pseudo);
        if (index > -1) {
            Array.prototype.splice.call(amisNotifies, index, 1);
            $scope.isChecked[id] = "fa fa-circle-o pull-right";
        } else {
            amisNotifies.push(info);
            $scope.isChecked[id] = "fa fa-check-circle-o pull-right";
        }

    } else {
        amisNotifies.push(info);
        $scope.isChecked[id] = "fa fa-check-circle-o pull-right";
    }
    console.log(amisNotifies);
}

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

Why is it that the screen orientation lock fails to function properly?

Currently, I am facing an issue with fixing the screen orientation to portrait for a specific page in my Ionic 4 application. I have tried utilizing the Cordova plugin from https://github.com/apache/cordova-plugin-screen-orientation Although monitoring t ...

Different methods for adjusting the bot's background hue

Currently, I have my Luis bot integrated into a SharePoint website using the iframe HTML element. I am looking to add some custom styling to it, specifically changing its background color. I found a tutorial that explains I need to clone the source code a ...

Mapping Services API for Postal Code Borders by Google

After hitting a dead end with Google Maps Marker, I am seeking help to replicate the functionality for users on my website. Specifically, I want to take a user's postal code and outline their boundaries using Google Maps API. If anyone has knowledge o ...

How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row co ...

Having trouble with Javascript in getting one-page scroll navigation to work?

Hey there, I am working on creating a one-page scroll navigation with some basic javascript to add a smooth animation effect that takes 1 second as it scrolls to the desired section. However, I seem to be experiencing an issue where it's not functioni ...

Visualizing connections between elements using SVG from JSON data files

As a newcomer to D3, I am facing challenges in visualizing my json file. My task involves plotting the locations (sites) as circles with their radius determined by the "amount" value. The concept of working with nodes and links is causing me great confusio ...

Learn how to dynamically toggle the visibility of tabs in CodeMirror with a simple button click

Currently, I am developing a Python editor for a website using the Code Mirror JavaScript library. There is a button called toggle invisibles that, when clicked, displays spaces and end-of-line markers. I also wanted to show tabs, which are not supported b ...

The performance of the animation on http://responsive-nav.com/ becomes erratic when viewed on Android devices

Recently, I came across a fantastic plugin that works perfectly on regular computer browsers. However, when I tested it on my android phone, the css3 animation for the dropdown appeared choppy and seemed to be dropping frames. Does anyone have suggestions ...

Convert HTML element to a JSON object

Here is an example of an HTML element: <div class='myparent'> <div> <div class="pdp-product-price"> <span> 650 rupees</span> <div class="origin-block"> <sp ...

Tailwind does not display font sizes using random values

I am attempting to adjust the size of a span element based on a number from a variable: export default async function Tags() { const tags = await getTags(); return ( <div> <Suspense> <div className="flex flex-wrap ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

ChartJS, introducing a new dataset

I'm looking for a way to showcase my 3 curves in a specific order: start with the first one, then after a 5000 interval, add the second curve, and finally, after another 5000 interval, include the third dataset. The code below currently updates a sin ...

JavaScript Tutorial: Storing HTML Text in the HTML5 Local Storage

I am looking to save the text that is appended using html() every time I click on a button. The goal is to store this text in HTML 5 local storage. $('#add_new_criteria').on('click',function(){ $('#cyc_append').html(&apo ...

Utilize Custom Field to incorporate background videos from websites like Youtube or Vimeo into your content

I've been working on implementing a video background for my website. I came up with a custom code to embed URL links from Youtube and Vimeo using "oEmbed". The process is functioning well, but I'm facing some challenges in setting the background ...

How can you set the Quill text editor to read-only mode in Vue after clicking a button?

I have a quill text editor that I want to customize the default setting to be readonly. When a button is clicked, this setting should toggle between true and false. Here is my component code: <template> <div ref="editor"></div> ...

applying the "active" class to both the parent and child elements

Looking for a way to apply an active class to both the parent and child elements when a user clicks on the child element within a list. The HTML structure is as shown below:- <ul class="tabs"> <li class="accordion"><a href="#tab1"> ...

Access various data from the local storage and display them inside a div container

I am trying to display the keys and their values for all the data stored in the local storage. Here is the HTML and JavaScript code I have written: // Setting some values in the local storage localStorage.setItem("lastname", "Smith"); localStorage. ...

A comma within an array element can disrupt the formatting of a spreadsheet

While populating an array with data, a peculiar issue arises where one of the elements contains commas in its value. Here is an example: "Trim marks at 103, 96, and 90". The code snippet below demonstrates adding the array elements to a spreadsheet object ...

When using .map() to iterate through an array of objects in Next.js, why does the data display in the console but

I'm facing an issue with displaying the elements of an array in HTML. I'm fetching data from the Bscscan API and while I can retrieve data successfully from the first API, the second one doesn't display the data in the local browser. I' ...

"Can you provide instructions on how to set the background to the selected button

How can I change the background color of a selected button in this menu? Here is the code for the menu: <ul id="menu"> <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></ ...