Exploring a custom directive in angularjs:
.directive('myDir', function() {
return {
restrict: 'E',
template: "..."
}
})
When considering the <my-dir></myDir>
tag, it appears to lack any default styling (or is not a block tag). My goal is to style it and position it correctly on my page. I have two options:
1) Utilize this template:
.directive('myDir', function() {
return {
restrict: 'E',
template: "<div class="layout">...</div>",
}
})
And apply css:
.layout {
/* styles */
}
However, this adds an unnecessary level in the DOM tree. If I were to use
<my-dir class="layout"></my-dir>
with the proper css, it would work but I'd need to remember to add the same class each time I use <my-dir>
in my code (not DRY).
2) This led me to consider adding style within the post-link function:
.directive('myDir', function() {
return {
restrict: 'E',
template: "...",
link: function(scope, element, attrs) {
element.addClass('layout');
}
}
})
Which approach is preferable? Are there any advantages or disadvantages that may not be immediately apparent?
UPDATE:
Using replace: true
in the directive definition is no longer recommended. When working with bootstrap, scenarios like
<my-dir class="visible-xs"></my-dir>
can be beneficial.