angularjsng-bind-html

How do you prevent ng-bind-html from adding closing tags?


I have two pieces of HTML I need to output the first is an opening tag of a div that represents my header, the second is the closing tag of the div that will represent the footer. Between the two I have dynamic content that I cannot control. I want headerHTML to include the opening div and CSS class and the footer to close the header div to wrap all the content that will be in between.

<ng-bind-html ng-bind-html="headerHTML" />

<ng-bind-html ng-bind-html="footerHTML" />

So after render it should look like:

<div class="myCSSClass">
   A bunch of dynamic content created between the two binds
</div>

However, what happens is this:

<div class="myCSSClass">
</div>
   A bunch of dynamic content created between the two binds
<div>
</div>

The problems is that it is auto adding the closing tag for the headerHTML when its not part of the content. This causes the page to render incorrectly. Is there another way to inject HTML content without it adding closing tag?


Solution

  • Under the hood, the ng-bind-html directive uses Node.appendChild. This means that it must attach a complete element. If the HTML omits a closing tag, the browser has to close the element. This is the way the DOM works. The browser can't split opening and closing tags between two .appendChild operations.

    To do what you want, use a component that transcludes contents:

    app.component("myComponent", {
        bindings: {
            headerHtml: '<',
            footerHtml: '<',
        },
        template: `
            <div class="myCSSClass">
                <div ng-bind-html="$ctrl.headerHtml"></div>
                <div ng-transclude></div>
                <div ng-bind-html="$ctrl.footerHtml"></div>  
           </div>
        `,
        transclude: true
    });
    

    Usage:

    <my-component header-html="headerHTML" footer-html="footerHTML">
       This content will be sandwiched between header and footer.
    </my-component>
    

    For more information, see