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

こ雲淡風輕ζ 提交于 2019-12-05 08:13:30

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

It can be achieved with angular element:

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

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

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