0

So I have this directive which will allow use declaratively hide or show elements:

<div cdt-visible-to="Admin,Moderator">...</div>

So our HTML becomes as declarative as possible. And this is what our directive looks like:

eDiscovery.directive('cdtVisibleTo', ['AuthService', function (AuthService) {

    return {

      restrict: 'AE',

      link: function ($scope, elem, attrs) {

        let cdtArray = String(attrs['cdtVisibleTo'] || '')
        .split(/[ ,]+/).map(i => String(i).trim()).filter(i => i);

        let ln = cdtArray.length;

        for (let i = 0; i < ln; i++) {
          let r = cdtArray[i];
          if(AuthService.hasPersona(r)){
            elem.removeAttr('hidden');
            return;
          }
        }

        elem.attr('hidden', 'hidden');

      }
    }
  }]);

So this is like a stand-in for ng-show.

My question is - what would a stand-in for ng-if look like?

What is the best way to remove elements from the DOM altogether with an Angular directive?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

1

You can use the .remove() method of Angular element to remove an element from the DOM: First get the angular element from your elem and then use the remove function

To do this perform:

angular.element(elem).remove();

I guess you want to remove it from the DOM if no one of the the Personas passed to the directive is authorized, so maybe you can use the following code:

var notAuthorized = false;
for (let i = 0; i < ln; i++) {
  let r = cdtArray[i];
  if(AuthService.hasPersona(r)){
    notAuthorized = true; //A Persona is authorized
    return;
  }
}

if (notAuthorized) {
    angular.element(elem).remove();
}

More info & methods of angular.element: https://docs.angularjs.org/api/ng/function/angular.element

Sergio Diez
  • 409
  • 6
  • 11