Skip to content

Instantly share code, notes, and snippets.

@bajzarpa
Last active February 8, 2017 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bajzarpa/ec4f5612186a985711fe0d3a2d4c2b24 to your computer and use it in GitHub Desktop.
Save bajzarpa/ec4f5612186a985711fe0d3a2d4c2b24 to your computer and use it in GitHub Desktop.
Angular.js directive to get user gravatar from user email
// npm install md5 --save
import md5 from 'md5';
let gravatarModule = angular.module('gravatar', [])
.directive('gravatar', () => {
const DEFAULT_AVATAR = "http://www.gravatar.com/avatar/000?s=200";
const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let isEmail = (email) => EMAIL_REGEX.test(email);
let getGravatarUrl = (email) => isEmail(email) ? `http://www.gravatar.com/avatar/${ md5(email) }.jpg?s=200` : DEFAULT_AVATAR;
let link = (scope) => scope.url = getGravatarUrl(scope.email);
return {
template: `<img ng-src="{{ url }}">`,
restrict: 'EA',
replace: true,
scope: { email: '=' },
link
}
}).name;
export default gravatarModule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment