Read more

AngularJS directive to format a text with paragraphs and new lines

Arne Hartherz
April 17, 2014Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

Also see simple_format helper for Javascript.

Posted by Arne Hartherz to makandra dev (2014-04-17 15:13)