Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 232
klesta Avatar asked Mar 12 '13 13:03

klesta


2 Answers

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
like image 197
Mark Rajcok Avatar answered Oct 10 '22 19:10

Mark Rajcok


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.)

like image 37
klesta Avatar answered Oct 10 '22 19:10

klesta