Crocodile
Crocodile

Reputation: 5845

Adding classes to the html markup in the custom directive's template

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>

Upvotes: 1

Views: 2822

Answers (1)

A.B
A.B

Reputation: 20445

Adding classes to directive when using replace set to false will add them to directive that is pretty much same as applying on div

if you set attributes on directive <some-widget class="orange red"> that will be replaced with but attributes will remain there like <div class="orange red">This is the template</div>

Actually what happens is that all the attributes of the original DOM node are merged with those in the template's root node

Working example see console to verify

 angular.module('app', [])
        .directive('someWidget', function () {
            return {
                restrict: 'E',
                replace: true,
                template: '<div>This is the template</div>',
                link: function (scope, element) {
                 
                  
                }
            };
        });
.orange{color:red;}
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
    <some-widget class="orange red">
       
       
    </some-widget>
      </div>

Upvotes: 2

Related Questions