How to recompile the directive when pasting into the DOM (angularjs)

Ok, so I created a let say directive

<calendar></calendar> 

It becomes visualized as I expected, so everything works fine. Now, my question is how to (re) visualize it when entering into the DOM? I don’t want to use it on my page all the time, I just want to dynamically add it and visualize it only when I need it (this is part of the module), say, ideally, I want it to look like

 $("body").append("<calendar></calendar>") 

How can I achieve this with angularjs?

+6
source share
4 answers

You need to write two lines below, wherever you enter your directive in the DOM, be sure to add the dependencies $document and $compile wherever you use it.

 var template = '<calender></calender>', body = $document.find('body'); body.append($compile(template)(scope)); 
+3
source

This can be achieved using the angular element:

 angular.element('body').append($compile("<calendar></calendar>")($scope)); 
+2
source

The sequence of actions is as follows:

  • Create a DOM element or an angular.element object:

     var calendar = angular.element('<calendar></calendar>'), 
  • Pass it to the $compile service. At this stage, you need to provide the required scope object:

     $compile(calendar)(scope); 
  • Add calendar element for document:

     angular.element('body').append(calendar); 

So it all looks like this:

 var calendar = angular.element('<calendar></calendar>'); $compile(calendar)(scope); angular.element('body').append(calendar); 
+1
source

You can use the $ compilation service to recompile it and use angular.element ('body'). add to add it to the page again. For instance:.

  var el = $compile( "<calendar></calendar>" )( $scope ); angular.element('body').append( el ); 
0
source

Source: https://habr.com/ru/post/982842/


All Articles