AngularJS - permission directive

klesta picture klesta · Mar 12, 2013 · Viewed 8.3k times · Source

I am trying to write directive that will evaluate user permissions.

In case user is not permitted to see given content

  1. the content will not be displayed (done, working fine)

  2. requests from controllers inside permission directive will not get fired.

Example:

Controller:

function MyController ($scope){
     // performing imediately server request, witch is allowed only for admin
     // therefore i will get error when non admin user access this page
}

Permission directive:

return {
        priority: 1000,
        restrict: 'E',
        link: (scope, element, attrs) => {
            var permission = attrs.permission;

            if (/*evaluating permission*/) { 
                // user has permission, no work for me
                return;
            }

            element.remove();
        }
    };

All together:

<permission permission="isAdmin">
    <div ng-controller="MyController">
    </div>
</permission>

This version is removing elements from DOM, but request in MyController still gets executed. Off course, I can make check for permissions in MyController, but I don't want to.

Thank for help.

Answer

Mark Rajcok picture Mark Rajcok · Mar 12, 2013

Your issue is that the controller will always be called before the link function executes. See this fiddle.

function MyCtrl($scope) {
    console.log('in controller');
}

myApp.directive('permission', function() {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            console.log('in link');

Log shows:

in controller
in link