javascripthtmlangularjsng-bind-html

Word Wrapping using ng-bind-html


I am using AngularJS to build a personal note management application. During so, I ran into a few problems where I get to choose my bug: Whether I should have an application that can't word wrap or one that can't sense the return key.

At first, my app wouldn't sense the return key or extra spaces, so, in my note directive, I replaced: <p>{{note.body}}</p> with: <p ng-bind-html="note.body | format"></p>


While it fixed the issue with the enter key, not it wouldn't word wrap:

App with ng-bind-html

Using ng-bind-html, automatic word wrapping fails - which would be horrible for my app, since I want it to be extremely flexible when it comes to resizing.

How to I fix this error?

Here's my format filter: angular.module('NoteWrangler') .filter('format', function (){ return function(input) { if(!input) return input; var output = input //replace possible line breaks. .replace(/(\r\n|\r|\n)/g, '<br/>') //replace tabs .replace(/\t/g, '&nbsp;&nbsp;&nbsp;') //replace spaces. .replace(/ /g, '&nbsp;'); return output; }; });

Note Directive:

```<div class="container note note-full">
    <h2>{{note.title}}</h2>
    <p ng-bind-html="note.body | format"></p>
    <p class="text-muted date">Posted on {{note.timestamp | date}}</p>
</div>```

If using the tag would be the only way to solve this, then I'll do it - after I make the background, border, etc. invisible w/ some CSS.


Solution

  • Add this css class to your <p> or whatever tag you want to use :

    .text-pre-wrap{
        white-space: pre-wrap !important;
    }
    

    Plus you only need this as your filter

    angular.module('NoteWrangler').filter('format', function () {
      return function (input) {
        if (input) {
          return input.replace(/\n/g, "<br />");
        }
      };
    });