Han
Han

Reputation: 2037

How to prevent trimming on bound values in Angular

Consider the following HTML fragment:

<div class="text-center">
    <h3>LAeq: <span class="monospace"><strong>{{ Laeq | paddednumber : 7 : 2 }}</strong></span> dB</h3>
</div>

Where paddednumber is a filter that adds leading spaces:

    myFilters.filter('paddednumber', function () {
    return function (value, width, decimals) {
        if (value === undefined) return;
        var result = value.toFixed(decimals);
        while (result.length < width) {
            result = ' ' + result;
        };
        return result;
    };
});

How do I prevent Angular from trimming the leading spaces the filter has added? I found the ng-trim option for the textarea and input directives, but the Laeq in the sample above is bound to a $resource and needs to be filtered to get the formatting right. I could of course do the formatting in the controller and then use ng-model on a textarea to bind to the formatted value in the scope, but I was hoping for a simpler solution in my HTML code.

Upvotes: 1

Views: 1742

Answers (1)

Josep
Josep

Reputation: 13071

Angular is not the one that it's trimming the leading spaces, it's your browser the one responsible for that. For instance, consider this example:

<div>
    Hello <span>               
                                Han</span>
</div>

This is pure HTML (no Angular), as you can see when the browser renders this markup, the browser ignores all the white spaces, carriage returns and tabs that appear until the next tag or blog of text. This is the standard behaviour of all browsers.

For instance if you do a right click on this same page and you select the option "view page source", you will see that there're lots of spaces, tabs and carriage returns that are being ignored. You may find something like this:

                        <a href="/review" title="Review queues - help improve the site">
                            review
                        </a>

Do you see all the characters that are being ignored by the browser?

That's why when you want to specifically say to the browser: "hey, this is a white space that I want you to render" you can use this symbol: &nbsp;, which is what you want to use for something like this.

But if you want your custom filter to render that symbol (&nbsp;) you need to either use its unicode equivalent, in this case \u00A0.

That's why I've changed your filter, like this:

.filter('paddednumber', function () {
    return function (value, width, decimals) {
        if (value === undefined) return;
        var result = value.toFixed(decimals);
        var spacesToAdd = width-result.length;
        for(var i=0;i<spacesToAdd;i++)
            result = '\u00A0' + result;        
        return result;
    };
});

Working Example

Upvotes: 3

Related Questions