1

How to properly remove element in dom model using angular directive?

.directive('restrict', ['AuthService', function (authService) {
    return {
        restrict: 'A',
        prioriry: 100000,
        scope: false,
        link: function () {
            alert('1');
        },
        compile: function (element, attr, linker) {
            var accessDenied = true;
            var user = authService.getUser();
            var attributes = attr.access.split(" ");

            for (var i in attributes) {
                if (user.roles.indexOf(attributes[i]) > -1) {
                    accessDenied = false;
                }
            }

            if (accessDenied) {
                element.children().remove();
                element.remove();
            }
        }
    }

this code throw exception in last line:

TypeError: Cannot read property 'childNodes' of undefined

directive works well for td or li elements, but wrong for a or div or span

<span data-restrict access='EditUser' class="glyphicon glyphicon-trash" ng-click="deleteUser(u)"></span>
Yuriy Mayorov
  • 961
  • 4
  • 15
  • 32

1 Answers1

0

Rather than do this, you could go a different approach, you could add a controller which sets a flag (accessDenied) on the scope based on the same condition, then use ng-if on your directive, or first child element failing that.

alexrogers
  • 1,514
  • 1
  • 16
  • 27