Last Updated: February 25, 2016
·
4.234K
· vkbalakrishnan

HubSpot Odometer plugin/directive for AngularJS

HubSpot have a nice odometer like number transitioning library at https://github.com/HubSpot/odometer. Recently I used this for an Angular.JS project and wrote a directive to implement it.

var el = document.querySelector('.some-element');

od = new Odometer({
  el: el,
  value: 333555,

  // Any option (other than auto and selector) can be passed in here
  format: '',
  theme: 'digital'
});

od.update(555)

The above code is a sample implementation from http://github.hubspot.com/odometer. For our use we will convert this into a directive which can be used in our views as below.

<odometer value='countToNumber'></odometer>

Here countToNumber is a model in our scope.

So, the code for the directive needs to accept the model and initialize the Odometer plugin.

angular.module('myApp')
  .directive('odometer', function () {
    return {
      restrict: 'E',
      scope : {
        endValue : '=value'
      },
      link: function(scope, element) {
        // If you want to change the format, you have to add the necessary
        //  parameters. In this case I am going with the defaults.
        var od = new Odometer({
            el : element[0],
            value : 0   // default value
        });
        // update the odometer element when there is a 
        // change in the model value.
        scope.$watch('endValue', function() {
          od.update(scope.endValue);
        });
      }
    };
  })

1 Response
Add your response

what about formatting?

over 1 year ago ·