Using Gravatar With AngularJS

12/06/2013
Share

Want to use Gravatar in your AngularJS app?
Use this simple directive to insert Gravatar images in your app.

Before you get started, you will need to make sure you have an MD5 hashed version of your users email address. Gravatar uses this hashed version of the email address in order to determine which avatar to display.

It’s simple in any back end language to generate this hash on page load, or send it down with your JSON model.

In Ruby

Digest::MD5.hexdigest(email_address)

In PHP

md5(email_address}

Now, Include this directive in your AngularJS application

 myApp.directive('gravatar', function() {
  return {
    restrict: 'AE',
    replace: true,
    scope: {
      name: '@',
      height: '@',
      width: '@',
      emailHash: '@'
    },
    link: function(scope, el, attr) {
     scope.defaultImage = 'https://somedomain.com/images/avatar.png';
    },
    template: '<img alt="{{ name }}" height="{{ height }}"  width="{{ width }}" src="https://secure.gravatar.com/avatar/{{ emailHash }}.jpg?s={{ width }}&d={{ defaultImage }}">'
  };
 });

You can change the “defaultImage” property to link to a default avatar to display when the user has no Gravatar.

Then simply drop the tag with attributes into your HTML

<span gravatar name="Bill Murray" width="50" email-hash="1726e726ac7163a6f"></span>