ng-include tag and SVG images in AngularJS

angularjs, html

Solution

Essentially you can't define your own void/self-closing tags in HTML. There are a limited number of these, as described at http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements :

area, base, br, col, embed, hr, img, input, keygen, link, menuitem, meta, param, source, track, wbr

Also, browsers effectively ignore the `/>`. So when you use an element that isn't in the list of void elements, such as `<ng-include ...`, such as in your example (wrapped in a `<div>`)

<div>
  <ng-include src="'resources/svg/mastercard.svg'" />
  <ng-include src="'resources/svg/paypal.svg'" />
</div>

the browser will parse it as

<div>
  <ng-include src="'resources/svg/mastercard.svg'">
    <ng-include src="'resources/svg/paypal.svg'"></ng-include>
  </ng-include>
</div>

and I suspect that causes the error you're seeing. The reason why the following works

<span><ng-include src="'resources/svg/mastercard.svg'" /></span>
<span><ng-include src="'resources/svg/paypal.svg'" /></span>

is that the browser recognises the closing `</span>` must close any tags opened since the opening `<span>`, and so parses it as:

<span><ng-include src="'resources/svg/mastercard.svg'"></ng-include></span>
<span><ng-include src="'resources/svg/paypal.svg'"></ng-include></span>

Problem

I've came across a strange issue. It's not like it's blocking something, but I thought that it would be better to understand this behavior. I use ng-include in AngularJS to include SVG images so I can style them with CSS. So this code works fine: ``` <ng-include src="'resources/svg/mastercard.svg'"></ng-include> <ng-include src="'resources/svg/paypal.svg'"></ng-include> ``` This works fine too: ``` <span><ng-include src="'resources/svg/mastercard.svg'" /></span> <span><ng-include src="'resources/svg/paypal.svg'" /></span> ``` But this results in Cannot read property 'insertBefore' of null error and only the first image shows up on the page: ``` <ng-include src="'resources/svg/mastercard.svg'" /> <ng-include src="'resources/svg/paypal.svg'" /> ``` Basically, you can use multiple ng-include tags in one container if you close them with with a separate statement, but if you write it in a short manner - it must be one per container to work. Why is that? Is there something fundamental about it that I'm missing and should know?

Original source