handling interaction between angular directives for authentication

http://stackoverflow.com/questions/25752498/handling-interaction-between-angular-directives-for-authentication/25754068#25754068

by Eduardo GarcĂ­a Sanz

HTML

<a like="">Dogs</a>
<a like="" auth-role="user">Birds</a>
<a like="" auth-role="admin">Whales</a>

CSS

a {
    display: block;
    padding: 1em;
    margin: 0 0 .5em 0;
    line-height: 1em;
    font-size: 20px;
    font-family: Arial, Helvetica, sans-serif;
    text-decoration: none;
    color: #333;
    background-color: #add6ff;
    cursor: pointer;
    transition: background-color 450ms;
}

a.liked {
    background-color: #a4f2c5;
    cursor: default;
}

JavaScript

var app = angular.module('app', []);

app.factory('user', function() {
    
    var roles = ['user'];

    return {
        hasRole: function(role) {

            return !role || roles.indexOf(role) > -1;
        }
    };
});

app.directive('like', function(user) {

    return {
        restrict: 'A',
        link    : function(scope, element, attrs) {

            element.on('click', function () {
            
                if (user.hasRole(attrs.authRole)) {
                    
                    element.addClass('liked');
                    element.off('click');
                    
                } else {
                
                    alert('Unauthorized.');
                }
            });
        }
    };
});