When defining a custom directive, both link and compile functions get the 'element' as an argument which comes handy for adding classes to it. However, if the directive is an 'Element' directive, and the 'replace' field is set to false (as trying to avoid using this depreciated field), the element argument in the compile and link functions is the original directive's element (<some-widget>), and not the element in the template(<div>), so any added classes will be ignored by the browser.
Question: What is the best practice to dynamically add classes to the HTML markup in the template? (I can obviously insert classes as strings, but that feels dirrrty)
angular.module('app', [])
.directive('someWidget', function () {
return {
restrict: 'E',
replace: false,
template: '<div>This is the template</div>',
link: function (scope, element) {
element.addClass("orange");
}
};
});
The resulting HTML will be as follows:
<some-widget class="orange">
<!-- The orange class is ignored-->
<div>This is the template</div>
<some-widget>