Last Updated: February 25, 2016
·
3.818K
· 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.