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

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Tips for choosing the remaining items in a multiple selection process

In my HTML form, I have a multi-select field that contains categories and the corresponding items within each category. My goal is to allow users to select individual courses or select an entire category (identified by values starting with "cat_") in orde ...

What steps do I need to take to incorporate Material UI icons into my REACT project?

After reviewing the documentation, I found it somewhat confusing with terms such as "MaterialIcon, SVGIcons, Icons". If you are interested, you can check out the link here. I am looking for a simple explanation of the process from installation to using th ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

What steps are involved in testing a nextjs endpoint with Jest?

One of my challenges is an endpoint responsible for user sign up: import { createToken } './token'; // Unable to mock import { sendEmail } './email'; // Unable to mock export default async function signUp( req: NextApiRequest, res: ...

What is the reason behind LESS displaying arithmetic operations as text instead of performing them?

Whilst composing the subsequent operations @a: 2px @variable: @a + 5; .margin-style{ margin-left: @variable; } The code above compiles into .margin-style{ margin-left: 2px + 5; } Rather than margin-left:7px; What could be causing this issue? ...

Effective Angular - ensuring all API calls are completed in a forEach loop before returning the final array

Struggling with the asynchronous nature of Angular, I'm faced with a challenge. My task involves looping through various cards where certain types require API calls while others do not. However, upon completion of the loop, only the cards that do not ...

What is the best way to center an image within its div, especially when the image size may vary and could be larger or smaller than the div wrapper?

Is there a way to horizontally center an image inside a div, regardless of the size difference between the image and its wrapper? I am aware of a Javascript solution, but I am specifically looking for a CSS-based solution. The following sample code does ...

Convert an array of string values into a JSON format

I need help with converting an array stored in my database to a more user-friendly format. Currently, it is saved as follows: ["size:medium","height:10cm"] This format makes it difficult to display in a table. I am wondering if there is a way to conver ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...

Generating data for a table by choosing a row from another table through ng-repeat

One of the functionalities I am working on involves a table where users can select an option and have that selection populate another table called 'User Details'. The table is populated with data retrieved from an API call in the angular controll ...

Develop a website using HTML and CSS for the front-end design, complemented by Java for the

I find myself at a standstill with a project I want to tackle, but unfortunately, my knowledge of modern web development, particularly full stack, is minimal. As a result, I am completely clueless on how to proceed. Here is what I am familiar with and what ...

Is the data fetched by getStaticProps consistently the same each time I revisit the page?

When utilizing routes to access a specific page like page/[id].js, the concern arises whether data will be refetched each time the page is visited. For instance, if you navigate to another page through a link and then return to this original page by pres ...

Clicking on a column or x-axis category in Highcharts will automatically include the job number in the page URL

Check out the code I've put together: http://jsfiddle.net/a9QwS/ I'm looking to add functionality where clicking on a column or x-axis label will append its data to the URL. For example, in PHP, I can do something like this: echo " <td sty ...

AngularJS Input field fails to update due to a setTimeout function within the controller

I am currently working on a project that involves AngularJS. I need to show a live clock in a read-only input field, which is two-way bound with data-ng-model. To create this running clock effect, I am using a JavaScript scheduler with setTimeout to trigge ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Storing data using mongoose does not alter the existing information

I encountered an issue with my code while trying to update an object fetched from a MongoDB. The object contains a map with an array, and I am pushing new values to that array within the map successfully. However, even though the object itself reflects the ...

Next.js encountered an issue when trying to read properties of null, specifically the 'push' property, resulting in a TypeError

I am utilizing the sweetalert2 library for displaying popups: export default function Home() { const MySwal = withReactContent(Swal) useEffect(() => { MySwal.fire({ showConfirmButton: false, customClass: { ...