Check if an Angular directive exists

All we need is an easy explanation of the problem, so here it is.

We’re doing a lot of work around dynamic directives in our Angular project, and one thing that came up as a nice-to-have was a way to have a generic directive that can list many different types of similar objects (e.g., messages, users, comments, etc.), by delegating to specific directives based on the objects’ types.

We call this directive, object-list and it will hopefully delegate to a number of different directives, if we can get it working properly.

The main issue we need to tackle is whether or not a directive that this object-list directive has been provided exists in our system. The way we’ve been checking this is by issuing a $compile against the target directive, linking it to a scope, and checking its HTML contents (e.g., var tmpElement = $compile('<div my-message'></div>')(scope);). This seems to work when the template for the target directive is referenced by the template option, but when we instead try to point to a templateUrl, the HTML contents are empty.

Here’s a Plunker, with the templateUrl approach in place (not working). You can comment it out and uncomment the template line to see the alert show up.

http://plnkr.co/edit/wD4ZspbGSo68v4eRViTp

Is there another way to check the existence of a directive? I’ll admit, this does seem a bit of a hack.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can use $injector.has to check if a provider or instance exists.

app.directive('objectList', function ($compile, $injector) {
  return {
    template: 'OK',
    link: function (scope, element, attrs) {
      var exist = $injector.has('myMessageDirective');
      ...
    }
  };
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply