tmartin314
tmartin314

Reputation: 4171

AngularJS filter function explanation

Here is a filter I'm adding to AngularJS:

angular.module('myApp', [])
  .filter('clean', function(){
    return function(input){
      return input;
    };
  })

Can someone explain like I'm five, why the extra anonymous function is needed in order for the data to be returned?

Basically why this doesn't work:

angular.module('myApp', [])
      .filter('clean', function(input){
         return input;
      })

I'm trying to understand what's going on here better so any help would be appreciated.

Upvotes: 4

Views: 698

Answers (1)

Omar Al-Ithawi
Omar Al-Ithawi

Reputation: 5160

We'll they could just do it the other way! But that's what frameworks about, standardization. Look at the service definition it works in the same way.

But if you look closely in the documents it says that .filter function and others like it should get providers not values. This helps in:

  1. Lazy or not instantiation.
  2. DI and all DI benefits, it lets you define dependency on per-filter basis.

Check the full fiddle http://jsfiddle.net/vAHbr/4/

angular.module('myApp', [])
.filter('discountcurrency', 
        // The provider, where we can encapsulate our filter 
        // creation code, without having to do JavaScript ninja 
        // stuff. As well as this is our chance to ask for 
        // dependencies.
        function ($filter) {
        var currency = $filter('currency');            

        // The actual simple filter function.
        return function (value) {
            return currency(value - 5);
        }
    });

Upvotes: 3

Related Questions