How to dynamically apply a CSS class to a new element in an AngularJS ng-repeat loop

Welcome to my custom list layout.

<a href="#/">go back</a>
<ul>
    <input type="text" ng-model="search">

    <li ng-repeat="item in items | filter:search | orderBy:'date'">
        {{ item.ID }} - {{ item.title }} - {{ item.date | date:"dd.MM.yy" }}
        <button ng-click="deleteItem(item.ID)">delete</button>
    </li>

    <form>
        <input type="text" ng-model="itemName">
        <input type="date" min="{{ date }}" max="{{ maxDate }}" value="{{ date }}" ng-model="itemDate">
        <button ng-click="addItem()">add</button>
    </form>
</ul>

When the controller adds a new item through a button click, it functions perfectly. However, I now wish to apply CSS3 animations exclusively to the newly added item. To do this, the new item must receive a specific class. How can I accomplish this with AngularJS?

Answer №1

To dynamically apply the class highlight-class to the last item in the list, you can use the following code snippet:

<li ng-class="{'highlight-class': $last}" ng-repeat="element in elements | filter:search | orderBy:'name'">
    {{ element.id }} - {{ element.title }} - {{ element.date | date:"MM/dd/yyyy" }}
    <button ng-click="deleteElement(element.id)">Delete</button>
</li>

Answer №3

When utilizing a function to include an item, it is possible to track the last inserted ID by setting a variable within the process of adding the item to the list.

To illustrate this concept, refer to the following example: http://jsfiddle.net/DotDotDot/Eb2kR/
In this case, a variable named lastInsertedId is created and utilized to assign a class in the ng-repeat block:

<span ng-class='{lastinserted: item.ID==lastInsertedId}'>{{ item.ID }} - {{ item.heading }} - {{ item.date | date:"dd.MM.yy" }}</span>

This implementation assumes that the IDs are unique numerical values, however, the approach can be adapted for different data sets as well.

$scope.addItem=function(){
        var dd=new Date($scope.itemDate);       
        $scope.items.push( {"ID":$scope.items.length+1, "heading":$scope.itemName, "date":dd.getTime()});
        $scope.lastInsertedId=$scope.items.length;
        }

By updating the last inserted ID in this manner, the selected class will be applied to the respective item.
Additionally, the lastInsertedId value can be unset within the delItem() method if necessary.

In scenarios where a more complex logic is involved (such as non-sequential or non-numeric IDs), you can implement a custom function within the ng-class. For instance, consider the modified implementation provided in this updated example: http://jsfiddle.net/DotDotDot/Eb2kR/2/:

$scope.amITheOne=function(item){
    return item.ID==$scope.lastInsertedId;
}

Subsequently, utilize the function as follows:

<span ng-class='{lastinserted: amITheOne(item)}'>

While the concept remains fairly simple with basic logic, it can be extended to incorporate more intricate criteria based on various attributes like ID, name, and date.
Enjoy experimenting with these possibilities!

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

Numerous Firebase queries triggering the "10 $digest() iterations reached" error

As an example, I aim to create a list structured like this: Apple - Steve Jobs Microsoft - Bill Gates Tesla - Elon Musk To achieve this, I will utilize two Firebase applications in conjunction with AngularJS. The first Firebase app is organized as follo ...

Using a personalized domain with a Cloud Function to send a POST request

While I may not be the most experienced with Node.js, I am quickly learning and have a good grasp of JavaScript. Currently, I'm working on a project where I am utilizing Cloud Functions to build an API. My goal is to use a custom domain to access this ...

What is the counterpart of "in" in Python when it comes to Javascript?

Currently, I am working on automating scripts in JavaScript using Jest and Puppeteer. Right now, I am facing a challenge where I need to verify a name. For instance, if I have a name like const name = Watson, James R. and I want to compare it with another ...

Ways to choose a LIMIT clause in MySQL when using Bookshelf with Node.js

I am currently utilizing the bookshelf plugin in Node.js to run MySQL queries. However, I am facing some difficulties with executing a LIMIT query. Here is an example: SELECT * from tableName LIMIT 2; This is how my connection in bookshelf looks like: B ...

Ways to determine the overall cost of a shopping cart using Vuejs Vuex

Running a business requires managing various aspects, including tracking the inventory. In my store, I have an array called basketContents that contains items with their respective quantities and prices. An example of how it looks is: state: { basketConte ...

The website is successfully loading the CSS file, but is failing to apply its styles

I am currently working on a React webpage that is hosted from Flask and called through Elixir. However, I am facing an issue where the HTML loads properly, but none of the CSS styles are displayed. Despite Chrome's developer tools showing that the CSS ...

Avoiding errors during radio value changes when loading a component in Angular

I need assistance with setting a date using radio buttons. I encountered an error when I tried to change the value while the component was loading. html.component.html ... <div> <input type="radio" name="period" [checked]= ...

What do you call this technique, and how can I replicate it? (Adjusting text)

Have you noticed the cool feature on ? It automatically changes the text midway through the page (Sketch is made for insert changing text here like you) after some time. I'm curious about how they achieved that and what it's called. I'm att ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Converting Array Class into an Array of Arrays using Typescript

Looking to convert an array class in typescript and pass it to another source. Seeking help on achieving this task in a clean and efficient manner. data : target[] = [{Name : "XXX", Age : "31",DOB : "20-12-1988", Resource: "Java"}, {Name : "YYY", Age : "2 ...

scrolling through a list using .slice choosing an excessive amount of items

Is it possible to create a dynamic pager that can be customized using parameters from the URL? I have noticed that when I hardcode the perTime variable, everything works fine. However, as soon as I try to use a parameter from the URL, the page starts behav ...

How to effectively handle null values in a JSON file

I have successfully implemented a feature to fetch data from a JSON file and display it on my webpage. However, I am facing an issue when trying to load images into an owl carousel. Specifically, I need to handle cases where the image URL is null and ski ...

Changing URI to File Object using JavaScript

I have successfully retrieved the URI of a selected file in my Ionic app using the cordova-fileChooser plugin. https://i.sstatic.net/NxXti.jpg Next, I used the cordova-plugin-filepath to obtain the absolute path of the file from the nativeURL on the phon ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

The Bookshelf JavaScript model is creating a never-ending cycle of saving and changing data

In the Bookshelf model provided below, the users password is hashed when the model is saved. However, an issue arises when changing the model.set() call to a model.save(), leading to an endless loop of saving and changing. var User = bookshelf.Model.ext ...

Is an Event Bus necessary for sibling communication? Or can a parent send its data as a prop instead?

After watching a tutorial on using an event bus to communicate between sibling components in Vue, I came across an interesting approach. The tutorial demonstrated passing data from a parent component to child components as props, then modifying that prop i ...

Removing Angular scope upon splice operation

Why does my entire list get destroyed when trying to remove an item using splice in JavaScript? HTML: <ul class="nav nav-tabs"> <li ng-repeat="pane in panes" ng-class="{active:pane.selected}"> <a href="" ng-click="select(pane)"> ...

How can I define the upper limit for the axis on an AngularJS polar chart?

Is there a way to set the maximum polar axis value to 100, regardless of the data received? This is my current code in progress: angular.module("app", ["chart.js"]).controller("ChartCtrl", function($scope) { $scope.labels = ["January", "February", ...

Pass the returned variable value from a request.get call to another function in NodeJS Express

I have a situation where I am calling a function that makes a request to get some JSON data and then fills in the variables from my router.get method. The issue I am facing is that the variables are getting their value inside the callFunc function, but wh ...

Identify when the input loses focus in a link directive

I have a query regarding an input that is using a link directive. Specifically, I am wondering if it's feasible to identify when the input loses focus within the link function of the directive. Below is the directive in question: appDrct.directive(& ...