1

I have two filters, that both use part of the code, that is identical and could be extracted as a function(helper). I could place it incide controller, but the main issue, I'm not sure how to pass it and make visible for filter to use it afterwards.

Is there a solution for this? Thanks.

Eugene
  • 4,352
  • 8
  • 55
  • 79

1 Answers1

1

Just declare a filter and a service in your angular module like this:

angular.module('myModule')
    .service('myFilterService', function () {   
            this.mySharedCode = function () {
                // Put your shared code here
            };
        })
    .filter('myFilter1', function (myFilterService) {
        return function (input, arg) {
            if (typeof input !== 'undefined') {
                // Do your filtering using myFilterService
                myFilterService.mySharedCode(...)
                return myFilteredInput
            } else {
                return myReturnValueIfInputUndefined;
            }
        }
    })
    .filter('myFilter2', function (myFilterService) {
        // Do your filtering using myFilterService like you did with myFilter1
    })

Assuming you have an item available on the scope, you can use your filter

In your controllers:

.controller('myController', function ($scope, $filter) {
    var filteredItem = $filter('myFilter')($scope.item, filterArg);
}

In your templates:

{{ item | myFilter : filterArg }}
Timothée Jeannin
  • 9,652
  • 2
  • 56
  • 65
  • I never said, that this filter is for `ng-repeat` and that it will be applied per each element of array. Those I don't need that in controller. – Eugene Mar 14 '14 at 10:41
  • Ok, no problem, it's just an example of how to share code between two filters using a service. Of course your filter can do whatever you want it to do ... Will update my answer to reflect that. – Timothée Jeannin Mar 14 '14 at 10:43
  • What I actually needed was already described in first comment. i.e. https://gist.github.com/jeserkin/9545559 – Eugene Mar 14 '14 at 10:47
  • 1
    It is using a `factory` instead of a `service`. You said the code that is identical can be extracted as a function so it's okay to work with one unique instance of the service for both your filters. On the other hand if you want separate instances for each of your filters, go with the factory solution ... – Timothée Jeannin Mar 14 '14 at 10:51