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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)