Last Updated: February 25, 2016
·
4.288K
· lukasz-madon

Permissions directive to show elements depending in access rights in angularjs

This is an angular directive that shows elements depending on user access privilege

 //ls is loginService
angular.module('app.directives')
.directive('accessLevel', function() {
  return {
    restrict: 'A',
    link: function($scope, element, attrs) {
      var prevDisp = element.css('display')
      , currUserRole
      , accessLevel;

      $scope.$watch('ls', function(ls) {
        currUserRole = ls.userRole;
        updateCSS();
      }, true);

      attrs.$observe('accessLevel', function(al) {
        if(al) {
          accessLevel = accessLevels[al];
        }
        updateCSS();
      });

      function updateCSS() {
        if(currUserRole && accessLevel) {
          if($scope.ls.hasAccess(accessLevel, currUserRole)) {
            element.css('display', prevDisp);
          }
          else {
            element.css('display', 'none');
          }
        }
      }

    }
  };
});

Remember, this is just for UX not a security feature. Have a proper check serverside.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

Angular apps often share the page with analytics and payment scripts that are not Angular modules. Those scripts execute on the same origin as the framework.

Security insights from Cside