Sunday, 23 November 2014

Create a Filter

Filters in AngularJs are a great way to manipulate your data as part of it being bound, and helps to keep your logic separated and reusable. AngularJs has some useful filters built in so it’s worth checking the in-built filter documentation first to see if the filter you’re looking for is already in existence. If it isn’t, then writing a filter couldn’t be easier.

JavaScript

Once you've created your AngularJs module you can attach a .filter function to it to create your filter. Here, I'm going to create a filter that takes a string and returns a substring of it based on parameters passed in at the point of the filter being called.

Like all other AngularJs functions, the first parameter is the name and the second parameter is the function that is the filter.

var myApp = angular.module('myApp', []);
myApp.filter('myFilter', function(){
    return function(input, argOne, argTwo){
        if(input == undefined) return;
        if(input.length < argOne + argTwo) return;

        var output = '';

        output = input.substr(argOne, argTwo);

        return output;
    };
});


All filters should return a function, which is called whenever the filter is applied to a piece of data within your application. You could do any setup logic that you only want to be run once outside of this returned function, but I've never had a need to do so. The function signature of this returned function is prescribed by AngularJs due to the way that you call it.

The first parameter is the input to the filter, the variable that you want to manipulate using your filter. From then on, additional parameters are any options that you'll want to pass to your filter in order to customise the manipulation of your variable. This is powerful as it allows you to make your filter as generic as possible.

The last thing required in this returned function is to return the manipulated variable at the end. This is then what is displayed (in the case of calling from the DOM) or assigned (in the case of calling within JavaScript).

Usage

In JavaScript

You'll need to inject $filter into your controller. The syntax for calling a filter in this method is:

myApp.controller('myController', ['$scope', '$filter', function($scope, $filter){
     $scope.controllerOutput = $filter('myFilter')('some long string', 2, 5);
}]);


First of all you're telling AngularJs which filter function you want it to call, using $filter. It's one parameter is the name of the filter that you created. This returns your filter's returned function that is immediately called, hence why you have multiple function signatures in this manner. An alternative way to write this would be:

var myFilter = $filter('myFilter');
$scope.controllerOutput = myFilter('some long string', 2, 5);


(This is pretty advanced functional programming, and a really powerful part of JavaScript. I thoroughly recommend looking at Douglas Crockford's writings on functions if you want to understand this better. I went on a day course of his called Fun with Functions, and it completely changed the way I thought about functions. You can watch a version of this here.)

So, in the second function call you populate the parameters that match your filter's returned function signature. It should be in the format that the first parameter is the value to be manipulated, and the subsequent ones are the options.

This will return a value, so make sure you have some variable ready to have this value assigned to it. One thing to note is that running your filter this way means that you have to call it each time you want to manipulate a variable in order for it to run. This is different from how it works in the DOM, so watch out.

In DOM

When used in the DOM filters work alongside AngularJs' two way binding, so it will run the filter every time the input changes and therefore update what the user sees.

The syntax for this is:

<input type="text" ng-model="userInput"/>
<p>Hello, user. This is your input: {{userInput}}</p>

<p>This is your subString: {{userInput | myFilter : 2 : 5}}</p>

As you can see we use the same double braces syntax expected for two way binding. At the start you put the variable (that should be hanging off $scope or be declared in an ngModel) that you want to be passed into your filter's input parameter. The next part of the syntax is my favourite because it makes me feel like I'm on the command line. When reading this statement it's like you're piping your value into the filter that you want to call. Any additional parameters that you need to send to your filter need to be separated by colons.

The variable userInput isn't modified at any point. What is displayed is the output value from your filter. Unlike with the JavaScript method you don't need to assign the output value as AngularJs handles it for you and displays the output to the user.

1 comment:

  1. Casinos with jackpots - SBJEON.net
    Best online 트리플 슬롯 casinos with jackpots – The Best and 바카라노하우 Top 메이저 토토 사이트 Bet! 라이브스코어 Casinos with Jackpots – 일반인 후방 Casino Software and Online Slots. Learn more and buy in.

    ReplyDelete