Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recompile a directive upon inserting into DOM (angularjs)

Okay, so I've created a directive let's say

<calendar></calendar>

It gets rendered as I expected so everything works fine. Now, my question is how to (re)render it when inserted into DOM? I don't want to use it on my page all the time, I just want to dynamically add it and render just when I need it to (it's a part of a module), let's say, ideally I want it to appear like

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

How can I achieve this with angularjs?

like image 623
Carteră Veaceslav Avatar asked Feb 22 '15 10:02

Carteră Veaceslav


People also ask

What does $compile do in AngularJS?

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

How do I invoke a directive in AngularJS?

In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the . directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive.

What is BindToController in AngularJS?

Angular introduces a new property to the directive definition object called bindToController. BindToController enables the inherited properties to be bound to the Controller without $scope object.

What is Prelink and Postlink in AngularJS?

Pre-linking function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Post-linking function Executed after the child elements are linked.


Video Answer


3 Answers

You need to write below two lines wherever you want to inject your directive element to DOM, don't forget to add $document & $compile dependency wherever you use it.

var template = '<calender></calender>',
    body = $document.find('body');
body.append($compile(template)(scope));
like image 65
Pankaj Parkar Avatar answered Nov 11 '22 13:11

Pankaj Parkar


It can be achieved with angular element:

angular.element('body').append($compile("<calendar></calendar>")($scope));
like image 32
Zaheer Ahmed Avatar answered Nov 11 '22 13:11

Zaheer Ahmed


The sequence of actions is this:

  1. Create DOM element or angular.element object:

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

    $compile(calendar)(scope);
    
  3. Append calendar element to document:

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

So all together it looks like:

var calendar = angular.element('<calendar></calendar>');
$compile(calendar)(scope);
angular.element('body').append(calendar);
like image 34
dfsq Avatar answered Nov 11 '22 11:11

dfsq