2

I want to add custom directive name to an element like we add attribute name and their values using attr() method in jquery .

For example supoose I have a custom directive named example-directive and I want to call this directive on an element programmatically like in the following js fiddle example I want to add example-directive on the div that has ID sam.

Could anyone tell me how to achieve this?

http://jsfiddle.net/RmDuw/383/

3 Answers 3

1

You were so close to do it. Here is the fiddler that is doing it and here is an article that explains it in more detail.

You've missed:

console.log(attrs['exampleDirective1']);

Edit:

As per your comment you can add the attribute with jQuery like in this also you can find the docummentation for .attr here

Sign up to request clarification or add additional context in comments.

3 Comments

I want to add directive name to the Div that contains Id "sam" . Like in following example on button click I can add attribute name on element using jauery attr() . Same way I want to add Directive name on div element that has id "sam" on button click. jsfiddle.net/ge87pgnf/2
In other words you want to use your exampleDirective1 on the div that has id=sam ?
@angle-bracket please look on my edit. it should do the trick. you can see the id with firebug or some inspecting tools
0

$compile is the key here. Assuming that you actually want to replace that div with the directive of yours. You need to find that element and then compile your directive html and replace it with that. Without compile it will not work and you'd just see the html.

function MyCtrl($scope, $element, $compile) {
    var element = $element.find("#sam");
    var compiled = $compile('<div example-directive1>{{message}}</div>')($scope);
    element.replaceWith(compiled);
}

Here is the jsfiddle.

Comments

0
  1. Set the attribute of the element using JQuery

    $('#id').attr('directive-name', '1');

  2. Compile the attribute

    $compile($('#id'))($scope);

Here is the jsFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.