eHx
eHx

Reputation: 181

AngularJS Directive - Adding class to created 'div' element

I'm trying to create a custom directive for my AngularJS project

Here's what I have so far :

.directive('testDirective', [

    function () {

        return {
            restrict: "EA",
            replace: false,
            transclude: false,

            link: function ($scope, el, attrs) {
                var param = {};

                param.className = attrs.customClass || 'default-class';
                param.distinctClassName = attrs.distinctClass || 'added-class';

                el.addClass(param.distinctClassName); // this works? :|

                var createdDiv = null;

                createdDiv = createdDiv || document.createElement('div');
                createdDiv.className = param.className; // this works...
                createdDiv.addClass(param.distinctClassName); // this doesn't work? :/
            }
        };
    }
]);


For now, this a very simple directive, but it will grow larger. I'm creating an element dynamically because I want to use it as a modal box, and I will append a div to the body.

I want to add a different class while keeping the original class to have all the default styling.

Here's what's happening:

Using <test-directive custom-class="first" distinct-class="second" /> in the template

Now, can anyone tell me why I can't add class but can change it directly? I know I must be forgetting something... but can't figure out what !

Upvotes: 0

Views: 9251

Answers (1)

PSL
PSL

Reputation: 123739

createdDiv.addClass(param.distinctClassName); does not work because it is a DOM element, it is not a jqlite wrapped angular element. And addClass is a function added on the jq wrapper and not available on the DOM element.

You would need to do:

angular.element(createdDiv).addClass(param.distinctClassName);

and el.addClass(param.distinctClassName) works because the element is an angular element (jq[lite] wrapped DOM element).

Leaving apart this issue, you could easily have a template for your directive and use ng-class bound to a scope property and you can get away from doing all these manually.

Upvotes: 6

Related Questions