FlavienBert
FlavienBert

Reputation: 1684

Angular : issue in my directive to get the original html content

I try too create a directive with angular. My goal is too get the original content from my html file in the compile or link function of my directive. Then update this content and for finish change the original content by the updated content in my template of my directive.

For exemple this is my index.html:

<my-directive> Hey this is my original content that I try to get! </my-directive>

This is my directive :

        .directive('myDirective', function() {
        return {
            restrict: 'AE',
            transclude: false,               
            template: '{{UpdatedContent}}',
            compile: function(tElement, tAttr) {
                console.log(tElement[0]);
            },
             ...

The probleme is that in my compile function or link I can't get my original content each time I tried to look the tElement object I get the "{{UpdatedContent}}".

UPDATE : ANSWER

In fact the solution is to use the function transcludeFn of the compile function.

Here an exemple who works :

     compile: function(elem, attrs, transcludeFn) {
     var markdownContent = {};    
     transcludeFn(elem, function(clone) { 
     /* clone is element containing html that will be transcludded*/
        console.log (clone.text());   
                });

My "clone.text()" is my original html. I hope this will help some of you!!

Upvotes: 1

Views: 992

Answers (1)

artur grzesiak
artur grzesiak

Reputation: 20348

You should set transclude : true, you should not do this: template: '{{UpdatedContent}}'.

If you want to get html of element on which your directive were placed in the link function just call:

tElement.html()

Btw. you always get {{UpdatedContent}} because you literally set it to be your template.

UPDATE Working PLNKR.

Upvotes: 1

Related Questions