1

I'm trying to add the material angularjs md-input-container to the DOM via a directive's compile function as following :

element.after(`
    <md-input-container md-theme-watch="true" flex>
        <label for="sampletext1">Champ texte</label>
        <input name="sampletext1" type="text"
               class="ng-tree-search">
    </md-input-container>
`)

But when I open the page, the element looses it's default behaviour and looks like this :

enter image description here

Instead it should look like this :

enter image description here

This only works when I add the element in the html, but in my case I want to add it via the link function of the directive that creates that treeview.

2
  • 1
    Why on Earth would you want to do that? Don't add elements with AngularJS directives in the DDO compile function. Instead find another way to achieve what you want. Commented Aug 1, 2017 at 16:18
  • Any error on console? Because I've tried with simplest example, it seems to be working fine.. There's possibility that treeview directive's compile function (has some error & thus) failing. Can you show the directives code in which you're performing above operation? Commented Aug 1, 2017 at 18:54

1 Answer 1

1

You need to compile the element's template first in link function of directive. This's how you can do that:

var elemHtml = `
            <md-input-container md-theme-watch="true" flex>
                <label for="sampletext1">Champ texte</label>
                <input name="sampletext1" type="text"
                       class="ng-tree-search">
            </md-input-container>
        `;
element.after($compile(elemHtml)(scope));

Don't forget to pass the $compile in function of the directive.

Working Plunker link: https://plnkr.co/edit/dKjanhRioFWtWcm4Hoki?p=preview

In question you said you've that in compile function but in title you're saying link function. Actually in compile function you don't need to use $compile in above case. (But if it's inside link function it's needed).

Example of having that inside compile function: https://plnkr.co/edit/By9Io583s6ZxffLyrHTt?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry my bad I meant link function, btw $compile function has solved the problem, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.