Using Gravatar With AngularJS


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




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 = '';
    template: '<img alt="{{ name }}" height="{{ height }}"  width="{{ width }}" src="{{ 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>