devo devo - 24 days ago 7
CSS Question

Access current custom directive element inside link function

I am manipulating DOM from the link function to add custom css using the directive attributes.

So here, first I will append one div with a class name, then find the div and add another div inside.

(function(){
"use strict";

var directive = function() {
return {
restrict: 'E',
link: function (scope, element, attrs) {
// Configuration
var id = Math.floor(Math.random()*100);
attrs.id = attrs.id || 'my-directive-'+id;
element.attr('id', attrs.id);

element.append('<h1>Here</h1>');

element.append('<div class="my-directive-background">');
element.find('.my-directive-background').css({'background-color':attrs.bColor});
// add css

element.find('.my-directive-background').append('<div class="my-directive-foreground">');
// add css
element.find('.my-directive-foreground').css({'background-color':attrs.fColor});
}
};
}

var directives = angular.module("directives");
directives.directive("myDirective",[directive]);

})();



<my-directive bColor="gray" fColor="red" />
<my-directive bColor="gray" fColor="green" />


The problem is, when I use more than one same directive, the find method detects previous element also.

How to find only the div belongs to current directive element?

Update: (Simple Solution)

@Shripal's solution works fine. But the problem was because of the element closing syntax.
It's simply fixed when I changed


<my-directive bColor="gray" fColor="red" />



to


<my-directive bColor="gray" fColor="red"></my-directive>


Answer

If jQuery is not added to your project, then find with class selector will not work.

I have created a working plunker using angular only with element.children()

Edit:

Updated plunker with jquery. I have optimized the code to first prepare the DOM and then appeded it to the element.