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

半城伤御伤魂 提交于 2019-12-07 03:54:30

问题


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?


回答1:


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



回答2:


It can be achieved with angular element:

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



回答3:


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



回答4:


You can use the $compile service to recompile it and use angular.element('body').append to append it to the page again. E.g.:

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


来源:https://stackoverflow.com/questions/28656596/how-to-recompile-a-directive-upon-inserting-into-dom-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!