Setting a class in AngularJS when there is a change in ng-repeat with pagination

I am currently attempting to assign a class to an item in a paginated list by simulating a click on the element within the directive's link property:

link : function (scope, element, attrs) {
        element.bind('click', function () {
        element.addClass("blue");
            });

}

Although this method works fine, I encounter an issue when navigating from one page to another. The classes that were applied to items on the first page are lost when moving to the second page. How can I ensure that all items retain the previously applied class?

Thank you.

Feel free to check out this Plunker for better understanding

Answer №1

To dynamically apply a CSS class based on user interaction, you can utilize ng-class and ng-click in AngularJS. This approach allows you to bind the class to a property of an element and toggle it when a specific action occurs, avoiding the need for a custom directive.

<input type="text"
  ng-init="initialValue = item.value"
  ng-change="updateValue($index, item.value, initialValue, item.id, 'value')"
  ng-model="item.value"

  ng-class="{'highlight': item.clicked}"
  ng-click="item.clicked = true"
/>

By using this method, the assigned classes will persist as users navigate across different pages within your application.

For more details about ng-class and ng-click functionalities, refer to:

https://docs.angularjs.org/api/ng/directive/ngClass

and

https://docs.angularjs.org/api/ng/directive/ngClick

Answer №2

It is recommended to store the changes in the data instead of directly manipulating the element in the directive.

$scope.items = [
  {id: 51,name: 'Hello',surname: 'other454r', highlight: false},
  {id: 52,name: 'Foobar',surname: 'othe44rr' highlight: false},
  {id: 53,name: 'Barfoo',surname: 'othe52rr' highlight: false},
  {id: 54,name: 'Magic',surname: 'other1r' highlight: false},
  {id: 55,name: 'Wand',surname: 'other4r' highlight: false}
];

Instead, utilize the angular ng-click and ng-class directives within your repeat loop as shown below:

<span ng-repeat="item in items"
    ng-click="item.highlight=!item.highlight"
    ng-class="{'blue': item.highlight}">
  {{item.name + ' ' + item.surname}}
</span>

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

Removing a specific object from an array in Node.js

Here is the structure of my database.json file: { "opened_tickets": [ { "userid": "4", "ticketid": "customer_info", "opened_timestamp": "1662543404514" }, ...

As two divs glide across the screen, the top div remains hidden from view

To enhance our user experience, we are tasked with creating a captivating screen saver featuring 3 images. The bottom image will remain fixed in its position. The middle image should move across the screen. Lastly, the top image will move at a faster ...

What methods can be used to customize the font and background color of a website for different user groups?

Trying to incorporate a template into my project. My client has requested the following: The regular user area should feature a blue background. The professional user area should have an orange background. Is there a way to set up a condition to change ...

Tips for preventing the occurrence of numerous instances of braintree.setup in Angular

I am encountering an issue with a Braintree payment form displayed in a modal window: $scope.displayModalBraintree = function () { $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () { ...

What is the hierarchy of fields in package.json?

After submitting a pull request to a repository to include a typings field in the package.json file, the maintainer suggested the following modification: - "typings": "./src/index.d.ts", - "main": "./src/index.js" ...

Having trouble sending a POST request to a nested array in Express JS

Welcome, this is my first post here so feel free to point out any missing information or incomplete details in my question :) I am currently working on a project where I need to make a POST request to an array within my data structure called features: co ...

I'm sorry, there seems to be a JSON error. The syntax is incorrect and it

I am facing a problem where I encounter an error when trying to post a JSON object. The error message reads: SyntaxError: JSON.parse: unexpected character Here is my JavaScript object: var $arr_data = { title: '', category: &apo ...

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

When launching JQuery UI Tabs in a new browser tab using ajax, the HTML from the ajax response will be immediately shown

I am currently in the process of upgrading from JQuery UI 1.8.14 to JQuery UI 1.10. Previously, when using v1.8.14 code, opening a tab in a new browser tab would cause the entire page to reload, activating the default tab (tabIndex=0). However, I am faci ...

Combining array objects in Node.js

Received an array in the request body: [ { "month": "JUL", "year": "2018" }, { "month": "JAN", "year": "2018" }, { "month": "MAR", "year": "2018" } ] The input consists of two parameters (month:enum and ye ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

Adding a click function to a div individually when they share the same class in HTML

My goal is to include 4 unique divs inside a timeline container: This is how I envision the structure: <div id="timeline" > <div class="timeline-bar t-1"></div> <div class="timeline-bar t-2"> ...

implementing toggle functionality for an array of items in ReactJS

I have an array and I am trying to create a show/hide feature for each item based on toggling. When I click on one item, it should expand while simultaneously hiding the previously expanded item. Here is the code snippet I have been working on: class App e ...

Editing JSON files - Substitute the $scope object with a new value

I am facing an issue with extracting data from an external JSON file for my application. Although most of the data loads into a DataTables table successfully, I am encountering problems with the $scope variable since it is referencing external data. Specif ...

Experimenting with AngularJS using karma and jasmine

I'm currently working on writing some unit tests. I encountered an error stating that angular is undefined, so my solution is to add the angular js file along with my other js files. In order to achieve this, I am attempting to npm install it... { ...

What's the most efficient way to iterate through this Array and display its contents in HTML?

I'm struggling to sort a simple array and I think the issue might be related to the time format. I'm not sure how to reference it or how I can properly sort the time in this array format for future sorting. //function defined to input values ...

How can I make this NextJS component show its width as soon as the page loads?

When I try to run this code to retrieve the browser's screen width, I encounter the following error: ReferenceError: window is not defined The commented-out code works fine with a default value of 0 and updates correctly when the browser width chan ...

Tips for retrieving and transforming the date time picker into the server format (toISOString)

I am attempting to utilize a datetime picker and convert it for server-side transmission, but I'm encountering issues. Here is my attempted code: <html> <head> <meta charset="utf-8"> <meta name="viewport" cont ...

Having issues with opening an exported Excel file using ExcelJS

While working on my JS project, I utilized the ExcelJS library. Everything was functioning smoothly with English characters. However, when I switched the language of my application to French and attempted to export the content as an Excel sheet, I encounte ...