I want to create a directive that checks whether an element should be present in dom based on the value received from the service (for example, check the user role).
The relevant directive is as follows:
angular.module('app', []).directive('addCondition', function($rootScope) { return { restrict: 'A', compile: function (element, attr) { var ngIf = attr.ngIf, value = $rootScope.$eval(attr.addCondition); if (ngIf) { value += ' && ' + ngIf; } attr.$set('ng-if', value); } }; });
At the end, the element has an attached ng-if attribute, but somehow it does not apply to the element and it still exists in dom. So this is obviously the wrong approach.
This script shows the problem: http://jsfiddle.net/L37tZ/2/
Who can explain why this is happening? Is there any other way of similar behavior? Existing ngIfs should be considered.
DECISION:
Usage: <div rln-require-roles="['ADMIN', 'USER']">I'm hidden when theses role requirements are not satifisfied!</div>
.directive('rlnRequireRoles', function ($animate, Session) { return { transclude: 'element', priority: 600, terminal: true, restrict: 'A', link: function ($scope, $element, $attr, ctrl, $transclude) { var block, childScope, roles; $attr.$observe('rlnRequireRoles', function (value) { roles = $scope.$eval(value); if (Session.hasRoles(roles)) { if (!childScope) { childScope = $scope.$new(); $transclude(childScope, function (clone) { block = { startNode: clone[0], endNode: clone[clone.length++] = document.createComment(' end rlnRequireRoles: ' + $attr.rlnRequireRoles + ' ') }; $animate.enter(clone, $element.parent(), $element); }); } } else { if (childScope) { childScope.$destroy(); childScope = null; } if (block) { $animate.leave(getBlockElements(block)); block = null; } } }); } }; });
It is very important to add priority to the directive, otherwise other directives attached to this element will not be evaluated!
javascript angularjs angularjs-directive
Foobar Dec 02 '13 at 10:01 2013-12-02 10:01
source share