Angularjs custom filter and dependency injection Angularjs custom filter and dependency injection angularjs angularjs

Angularjs custom filter and dependency injection


The answer is opposite to your question. Angular injects only into factory function but not into resulting function:

   .filter('newBookFilter', function($log, ...){ // <- factory function       return function(input, ...){              // <- resulting function       };   })

Factory function have arbitrary injected parameters. Resulting function have fixed parameters.

Second reason is that you can do some initialization in factory function. This is useful for example when you define new directive. Also factory returns closure which can capture variables and arguments from factory function. See example below. It uses dependency injection to get logging object. Here is full example.

  .filter('joinBy', function ($log) {     // <- injected here    return function (input, delimiter) {  // <- used here      var res = (input || []).join(delimiter || ',');      $log.info(res);      return res;    };  });


I think of Angular factory, service, filter, directive wrappers as ovens that create JavaScript objects and functions with Angular flavors. So, to borrow the same style from Vasiliy's answer:

// Don't use this code in a real app. It's just to illustrate a point.angular.module('App', [])// The following oven makes an Angular flavored JavaScript function that // formats a currency.service('currencyBadFilterFn',  // We inject a built-in Angular filter, currencyFilter, into our oven  function(currencyFilter) {     // oven produces a function that can be used in other places in Angular code    return function(number) {      // produced function returns a currency-formatted number when used      return currencyFilter(number)       }  }).controller('MainCtrl',  function($scope, currencyBadFilterFn) {    $scope.amount = currencyBadFilterFn(10) // $10.00  })

As you can see, the same pattern is used in creating services. Here, we are creating a service that returns a function that we can use in other places in our code.

The first function, the oven function, along with the .service or .factory or .filter wrapper, tells Angular how to build your function. The return value of that first function is what you will use in your code.


This is how I did it.

myApp.filter("myCustomDateFormatter", ['MyFactoryWithCustomFunctions', function (InjectedCustomFunction) {    return function (input) {        return InjectedCustomFunction.GetDateFromDotNetJson(input);    }}]);