I wrote my first AngularJS filter today. I needed to render HTML although I used Haml for templating and it was my first time implementing the ng-bind-html directive.

Here’s a pattern that illustrates what I achieved. I’m using a simple example to illustrate the powerful concept of filtering.

controller.js.coffee
1
2
3
4
5
6
7
8
app = angular.module("ExampleApp", [])

app.filter "whatAmI", ->
  (statement) ->
    if statement
      "<span class="answer-true">I'm true</span>"
    else
      "<span class="answer-false">I'm false</span>"
index.html.haml
1
2
3
4
5
6
7
!!!
%html(ng-app="ExampleApp")
  %head
  %body
    .row-fluid
      %span(ng-bind-html-unsafe="(1 > 2) | whatAmI")
      %span(ng-bind-html-unsafe="(1 < 2) | whatAmI")

The first filter returns I'm true.

The second filter returns I'm false.

Notice that curly brackets are not used in the ng-bind-html statements.

Helpful Links:

Comments