devo devo - 1 year ago 85
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.

"use strict";

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


element.append('<div class="my-directive-background">');
// add css

element.find('.my-directive-background').append('<div class="my-directive-foreground">');
// add css

var directives = angular.module("directives");


<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" />


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

Answer Source

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()


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download