Adding a custom filter to your AngularJS app

Filters are a very good opportunity to format your data. Once you have finished the custom filter you can use them in your whole application.

  1.  The first step is to create an AngularJS app
    var app = angular.module('myApp', []);
  2. Create a controller
    app.controller('MainCtrl', function($scope) {
      $scope.date = new Date();
    });
  3. Now let’s create our custom filter
    app.filter('time', function($filter) {
      return function(input) {
        return input.toTimeString()
          .replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
      };
    })

    This is a very simple filter, but this is ok for the moment.

  4. Finally we use the new filter in your templates :-).
    <p>{{date | time}}</p>

This is very easy isn’t it? Here you can find the demo on Plunker.

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>