AngularJS - permission directive

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.

I tried another approach and put removal of element into compile function. According to log, it is executed BEFORE controller, so it is right place. Anyway the request was still fired. So I tried just as a blind shot remove element children (I know, it does not make sense, removal of element should be sufficient and should remove children also).

But it worked!

compile: function(element) { var children = element.children(); children.remove(); element.remove(); }

It is working, but I am not sure how much OK it is (e.g. future version Ang.)

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

If I were you I would make a call to the server and check if they are authorised for access.

Doing this with a directive does not really make sense.

Directives are generally for manipulating dom and this is authorisation confirmation should generally be handled in the controller and then have the result of that trigger an event.

Then have your directive be listening for that event and manipulate the dom if they got access from the server.

Otherwise anyone could easily just inject whatever they wanted and see your admin panel.

If your not sure what I mean let me know I can expand the answer if you need me to.