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:

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

This is the directive, in CoffeeScript syntax:

Copy
@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 = _.map paragraphs, (lines) -> lines.split('\n')

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
almost 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