0

I want to create an attribute directive like ngDisabled to enable or disable elements if some specific role is present on my service.

angular.module(...)
.service('RolesSerivce', function() {
    this.hasRole = function(roleName) {
         return this.roles.indexOf(roleName)>1;
    };
    this.setRoles = function(rolesArr) {
        this.roles = rolesArr;
    };
    this.setRoles(['ROLE_CAN_CLICK'])
}).direcive('hasRole', function() {
    ??????????????????
    // use RolesSerivce.hasRole inside implemetation
    ??????????????????
});

On my HTML I want to use the directive like this:

<button has-role="ROLE_CAN_CLICK" ng-disabled="extraValidation > 0">Click me</button>

On the example above, the has-role directive must override the ng-disable, it must be mandatory. But the ng-disable must run when the has-role is true.

My question, can someone help me with the directive implementation? How can I do this?

Example with bug

http://codepen.io/betonetotbo/pen/rrazzY

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Beto Neto
  • 3,962
  • 7
  • 47
  • 81

2 Answers2

0

Try this:

angular.module(...)
.service('RolesService', function() {
    this.hasRole = function(roleName) {
         return this.roles.indexOf(roleName)>1;
    };
    this.setRoles = function(rolesArr) {
        this.roles = rolesArr;
    };
    this.setRoles(['ROLE_CAN_CLICK'])
}).directive('hasRole', function(RolesService) {
    return {
    link: function (scope, element, attrs) {
        $(element).removeAttr('ng-disabled');
        if(RoleService.hasRole(attrs.hasRole)) {
            $(element).removeAttr('disabled');
        } else {
            $(element).attr('disabled', 'disabled');
        }           
    }
    };
});
Aashish Koirala
  • 448
  • 5
  • 12
  • This will not work, I need to leave ng-disabled running if it has the role. Can you provide a https://jsfiddle.net/ – Beto Neto Sep 02 '16 at 17:10
0

Create a truth table:

                      (extraValidation > 0)==true  (extraValidation > 0)==false

ROLE_CAN_CLICK==true        DISABLED                     ENABLED

ROLE_CAN_CLICK==false       DISABLED                     DISABLED

Create an expression that matches the truth table:

<button ng-disabled="(!ROLE_CAN_CLICK) || (extraValidation > 0)">
     Click me
</button>
georgeawg
  • 48,608
  • 13
  • 72
  • 95