Reputation: 4627
In Angular, I do stuff like this all the time:
<div ng-controller="myCtrl">
<input type"text" ng-model="model.name">
</div>
And I know that ng-controller
and ng-model
are Angular directives. I also know that I can make my own directives and use them like this (among others):
<div photo photo-caption="caption"></div>
<photo caption="caption" src="image.jpg"></div>
Now that's great. But is it possible to do something like this:
<photo="Tom's Cat" src="cat.jpg"></photo>
Any insight would be greatly appreciated. Thanks!
Upvotes: 0
Views: 185
Reputation: 48211
No, you can't have a tag name have a value. Only attributes can have values.
I am not sure this is what you are after, but a few built-in directives support two forms: attribute (A) and element (E).
E.g. ngSwitch
can take on of two forms:
Attribute: <ANY ng-switch="expression" ...>
Element: <ng-switch on="expression" ...>
Thus, the expression
that needs to be evaluated is defined either on the ngSwitch
attribute (if it is present) or on the on
attribute (if ngSwitch
is used as a custom tag).
In the directive's link function, this is implemented like this:
link: function (scope, elem, attrs) {
var watchExpr = attrs.ngSwitch || attrs.on;
...
So, it first looks for an attribute named ngSwitch
(normalized name) and if it's not found (or is empty) it looks for an attribute named on
.
You could implement a similar feature, if you want your photo
directive to support different forms:
<div photo="My cool photo" src="..."></div>
or<photo caption="My cool photo" src="..."></photo>
e.g.:
.directive('photo', function () {
return {
restrict: 'AE',
...
link: function photoPostLink(scope, elem, attrs) {
scope.caption = attrs.photo || attrs.caption;
...
}
};
});
Upvotes: 1