ng-User
ng-User

Reputation: 243

apply css animation to specific html element using angularjs

please check first the demo on plnkr.

My problem is: this animation will be applied to all elements in html, cause in css is defined .ng-enter .ng-leave etc.

I am trying to apply it to a specific class name. In my case, it's <li class="specific">

And in CSS I've tried following:

.specific.ng-enter /*(does not work)*/
.specific-ng-enter /*(does not work)*/

With these code above, I can add and remove items but without animation.

How should the code be in css ?

Upvotes: 0

Views: 163

Answers (2)

gkalpak
gkalpak

Reputation: 48212

Actually, there are a couple of possible issues with the code:

  1. You are using ngRepeat on your <ul> (I cannot be 100% sure that this is not what you want but it is highly improbable). ngRepeat will "repeat" (clone" the element it is on, so in your case you are creating multiple <ul> elements (instead of multiple <li> elements, as one would expect).
    Moving ngRepeat o the <li> will solve the animation problem and result in the intended HTML code (1 <ul>, multiple <li>).

  2. Your CSS defined transition with every class, while it would suffice to define one rule:

    .top.ng-enter, .top.ng-leave { // ...define transitions here }

  3. In order to avoid possible CSS specificity issues (especially later on, when your CSS grows in size and complexity), you should include the .ng-enter/leave class selector in the rules with .ng-*-active:

    // Instead of just: .top.ng-enter-active {...

    // You should use: .top.ng-enter.enter-active {...

  4. Finally, you can group identical rules together, to save space and make your code more DRY (e.g. .top.ng-enter rule === .top.ngleave.ng-leave-active rule).


Your final code should look like this:

<!-- HTML -->
<ul>
  <li class="top" ng-repeat="item in items">{{item}}</li>
</ul>

/* CSS */
.top.ng-enter,
.top.ng-leave {
  -webkit-transition: 1s;
  transition: 1s;
}

.top.ng-enter,
.top.ng-leave.ng-leave-active {
  margin-left: 100%;
}

.top.ng-enter.ng-enter-active,
.top.ng-leave {
  margin-left: 0;
}

See, also, this short demo.

Upvotes: 1

Jay Shukla
Jay Shukla

Reputation: 5826

Just give class to your <ul> like this.

<ul class="my-anim" ng-repeat="item in items">
   <li class="top">{{item}}</li>
</ul>

Working Demo

Upvotes: 1

Related Questions