In my quest to develop a directive that can impact target elements in various ways, I have encountered three possible scenarios: 1. leaving the element unchanged, 2. removing all other directives before compilation to restrict user interactions (such as ng-click), or 3. completely eliminating the element.
While I have achieved success with all three options on specific elements, I faced an unexpected issue when applying option 2 to a button element. Rather than simply removing the ng-click directive, it resulted in a peculiar behavior where the event listener was duplicated. Despite there being no duplicate ng-click directives attached to the element upon inspection, clicking the button triggered the action twice.
Below is the current implementation of the directive along with the mock model I am currently utilizing.
return {
restrict: 'A',
priority: 1500,
compile(elem, attr) {
let action = () => { /**/ };
const currentLocation = $location.path().split('/')[1];
const permissionsLocation = appConfig[currentLocation];
const fullPath = attr.permissions;
if (_.has(permissionsLocation, fullPath)) {
const permLevel = _.get(permissionsLocation, fullPath);
if (permLevel === 'disable') {
action = (scope, element) => {
attr.$set('disabled');
elem.css({
cursor: 'not-allowed'
// 'pointer-events': 'none'
});
elem
.addClass('no-permissions')
.removeAttr('ng-click')
.removeAttr('ng-keyup')
.removeAttr('ng-change')
.removeAttr('ng-touchstart')
.removeAttr('ng-touchend')
.removeAttr('permissions');
$compile(element)(scope);
};
} else if (permLevel === 'destroy') {
action = (scope, element) => {
element.remove();
};
}
}
return {
pre(scope, element) {
action(scope, element);
}
};
}
};
The model:
appConfig.location1 = {
thing1: {
perm1: 'disable',
perm2: 'destroy',
perm3: 'destroy'
},
thing2: {
perm4: 'disable'
}
};
This is how I would apply the directive:
<button ng-click="blah()" permissions="thing1.perm1"></button>