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.

3
  • 1
    This answer may suit your needs: stackoverflow.com/a/21451815/1225328. Commented Mar 14, 2014 at 9:41
  • Does same principle work with passing argument to filter? Commented Mar 14, 2014 at 9:52
  • 1
    You would simply need to inject the factory within your filter: .filter('YourFilter', function(YourFactory) {...}) Commented Mar 14, 2014 at 10:09

1 Answer 1

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 }}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
What I actually needed was already described in first comment. i.e. gist.github.com/jeserkin/9545559
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 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.