0

I am wondering if I can make an Angular Js directive then I can use it again on the run time

here is a simple example

app.directive('w34Directive',function(){
return{
    template : "<p>test</p>"
  }
}) 

and here is the HTML

<div w34-directive></div>

but if I have a button with ng-click function that do the following function in the controller

var elem = document.querySelector('.myContainer');
angular.element(elem).append("<div w34-directive></div>");

which mean that a new DOM uses the directive will be generated but actually the angular directives fire once on the page load so when I add the new DOM it just add an empty div tag without the template of the directive which is in this case :

<p>test</p>

any idea about how to overcome this ?

2
  • What you're looking for is how to $compile your directive once it is on the page. My question is why are you attempting to add the directive after the page has already been compiled? Commented Oct 13, 2015 at 18:52
  • dom code doesn't belong in controllers. Often a sign that should be working with data model not dom...and let angular manage the dom Commented Oct 13, 2015 at 19:01

1 Answer 1

1

Yes, you can do it using :

$compile

Exemple :

 var el = $compile( "<div w34-directive></div>" )( $scope );
 angular.element(elem).append( el );
Sign up to request clarification or add additional context in comments.

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.