Quantcast
Channel: Terkildsen's Blog » javascript
Viewing all articles
Browse latest Browse all 10

Avoid the empty span-tag when using ng-include in AngularJS

$
0
0

Inserting HTML-templates via ng-include in AngularJS is a smart way to reuse code in your webapps. That way, you can have code in a separate file or in a separate block of code in the same file, and then insert the block of code whenever you need it.

Normally, you would have a block of code – just like the following:

<script type="text/ng-template" id="tpl1">
    <img src="img/pizza-pic1.jpg" alt="">
    <a href="#" class="title food-and-drink-cat h-50">
        <h3>Pizzasten</h3>
    </a>
</script>

You then insert the block of code in the following way:

<div ng-include="'tpl1'" ng-class="article.class">
</div>

This code will insert the template into the div-element. However, there is one small problem. If you inspect the result in Chrome Developer Tools, you will notice that AngularJS automatically inserts empty spans. Something like the following:

<span class="ng-scope">
</span>

AngularJS inserts this code in order to keep track of the current scope. However, I think it’s a mistake, and sometimes the empty span-tag messes with the layout of the page. Therefore, I investigated why this happens.

First of all, you can safely remove the empty span-tag. AngularJS doesn’t barf at you. Second, removing the empty span-tag is very easy. You just have to remove all spacing between the script-tag and the HTML. Just like so:

<script type="text/ng-template" id="tpl1"><img src="img/pizza-pic1.jpg" alt=""><a href="#" class="title food-and-drink-cat h-50"><h3>Pizzasten</h3></a></script>

This removes the empty span-tag – without consequences for AngularJS. I know that this solution isn’t pretty – I like to have my code formatted nice and pretty – but it works, and this is the important part.



Viewing all articles
Browse latest Browse all 10

Trending Articles