Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an Angular directive exists

Tags:

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.

like image 236
Monkey34 Avatar asked Sep 11 '13 23:09

Monkey34


1 Answers

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');       ...     }   }; }); 
like image 93
Buu Nguyen Avatar answered Sep 28 '22 06:09

Buu Nguyen