devqon
devqon

Reputation: 13997

Angular ng-repeat animate once

I am using ngAnimate to animate entries in an ng-repeat. When loading the data all elements are animated as I have defined in my css:

.chat-message.notice.ng-enter {
    -webkit-animation: rubberBand 1s;
    -moz-animation: rubberBand 1s;
    -ms-animation: rubberBand 1s;
    animation: rubberBand 1s;
}

This works when a notice is appended with the following html:

<ul>
    <li class="media chat-message pointer fade-animate"
        ng-repeat-start="message in guestbook.messages track by $index"
        ng-if="!message.bot">
        <!-- more html -->
    </li>
    <li class="chat-message notice" ng-repeat-end ng-if="message.bot">
        <div>
            <p class="text-center">
                {{ message.message }}
                <small>({{ message.date | amTimeAgo }})</small>
                <span class="close pull-right" ng-click="guestbook.remove(message)">&times;</span>
            </p>
        </div>
    </li>
</ul>

However, when a new message is appended (at the top), every element is again animated. Is there a way that elements animate only once? That when a new message is appended to the array, only that element will animate?

JSFIDDLE

EDIT

After a few clicks on a 'new message', I can see not all notices are animated. Maybe it has something to do with the ng-repeat-start and ng-repeat-end?

Upvotes: 2

Views: 684

Answers (2)

Michael Money
Michael Money

Reputation: 2449

Even above answer fixed the problem, my solution might be helpful in other scenarios. The fix is pretty straightforward.

Use Angular varible $first and just add CSS class for the first element using ng-class directive in your HTML. In this example, class "first" will be added only to first element in ng-repeat:

ng-class="{'first': $first===true}"

and then apply animation rules to element with "first" CSS class

.chat-message.notice.first.ng-enter {
    color:red !important;
    font-weight:bold;
    animation: rubberBand 1s;
}

Updated JSFIDDLE: http://jsfiddle.net/t6x3a1zj/7/

Upvotes: 1

Vassilis Pits
Vassilis Pits

Reputation: 3848

If understood correctly just change this:

$scope.messages.unshift(message);

to this:

$scope.messages.push(message);

Upvotes: 2

Related Questions