Posted over 5 years ago. Visible to the public.

AngularJS directive to format a text with paragraphs and new lines

If you are using Angular and want something like Rails' simple_format which HTML-formats a plain-text input into paragraphs and line breaks, this directive is for you.

Any HTML fragments inside that text will still be escaped properly.

Use it like this, where your text attribute specifies something available in your current scope:

<simple-format text="email.message"></simple-format>

This is the directive, in CoffeeScript syntax:

@app.directive 'simpleFormat', -> restrict: 'E' scope: true template: """ <p ng-repeat='lines in paragraphs track by $index'> <span ng-repeat='line in lines track by $index'> <br ng-hide='$first' /> {{ line }} </span> </p> """ link: (scope, element, attributes) -> scope.$watch attributes.text, (text) -> scope.paragraphs = [] if text? # remove weird newlines text.replace /\r\n|\r/g, '\n' # split lines and paragraphs paragraphs = text.split('\n\n') scope.paragraphs = paragraphs, (lines) -> lines.split('\n')

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Arne Hartherz
Last edit:
about 5 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more