Monkey34 Monkey34 - 1 year ago 152
AngularJS Question

Check if an Angular directive exists

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,

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
directive has been provided exists in our system. The way we've been checking this is by issuing a
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
option, but when we instead try to point to a
, the HTML contents are empty.

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

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

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download