Animating width of element based on dynamic value in AngularJS

876 Views Asked by At

Just wanted to share something in hopes that it can save time for someone else. I struggled for a while with this seemingly simple concept but couldn't find much out there that matched my specific needs.

The Problem:

I was building a game in AngularJS that prompts users to click/tap an ng-repeat element to make a choice based on scenarios that arise. There is a persistent score meter/bar. I wanted its width to animate to a percentage value calculated using the point value of the selected ng-repeat item. It's something I'm used to doing easily in jQuery but Angular was throwing me for a loop.

The Solution:

I ended up using a function in the ng-style directive on the element I wanted to animate. Since that element (the score bar) was in index.html, I also used rootScope.

So, when I got the point value of the selected item in my controller, like this:

$scope.getPoints = function(choice){
    $rootScope.earnedPoints = $rootScope.earnedPoints + choice.point_value;   
};

I could calculate the percentage and animate the score bar on the rootScope, like this:

 $rootScope.maxPoints = 100;
 $rootScope.earnedPoints = 0;
 $rootScope.updatePoints = function(value){
     if($rootScope.earnedPoints <= $rootScope.maxPoints){
         return {'width': ($rootScope.earnedPoints / $rootScope.maxPoints) * 100+'%', 'transition': 'width 1s' , '-webkit-transition': 'width 1s'};
     } else {
          return {'width': 100+'%'};
     }

Then, in the view, the updatePoints function is applied to the score bar element via ng-style, like this:

<div class="scoreBarInside" ng-style="updatePoints(value)"></div>

So, now, when a choice is clicked/tapped, the percentage is calculated and the score bar is animated according to that percentage.

Here's the fiddle: http://jsfiddle.net/bjDesign/0mLksrym/18/

If anyone has a better solution, I'd love to see it. I'm really digging Angular a lot...it just sometimes seems to be a struggle to figure out how to achieve the kind fluidity of movement in the UI that I like to provide for my clients using jQuery.

0

There are 0 best solutions below