Christof Aenderl
Christof Aenderl

Reputation: 4512

AngularJS directive: attr with name of other directive

A simple example to explain my case:

I have a directive for labels

<input label="{{obj.label}}"/>

But for some other directives I want to use an attribute with name "label"

<other-directive label="My label"></other-directive>

just as an attribute, not processing the label-directive.

I could just rename the attribute to e.g. "my-label":

<other-directive my-label="My label"></other-directive>

but it would be nice to use "label" as an attribute name.

Upvotes: 0

Views: 53

Answers (1)

Wade Tandy
Wade Tandy

Reputation: 4144

As @ExpertSystem points out in the comments to the question, angular really has no way of knowing out of the box whether your directive should be applied in one case versus another. The only way I can think of to get around this is to include logic in your directive's compile function that knows how to determine whether it should be applied or not. This plunker demonstrates how I would accomplish this. You basically need to return two different link functions from the compilation phase; one if your directive should be applied (in this case adding a label before the input), and a different one if it should be skipped. You are then free to use that as an argument to a separate directive. This may not work if your directive needs to do things like transclusion or isolated scopes (things that angular doesn't like two directives on the same element to do).

I'd be very sparing with how you use this, however, as it will create an inconsistent API for other developers who may be working with this code. They may not know when the directive will apply and when it won't.

Upvotes: 1

Related Questions