0

I'm new to angular and trying create a custom filter which requires a service. I followed the answer here https://stackoverflow.com/a/43506252/15817005. It solved my issue partially.

Registering filter

angular.module('filters',[]).filter('dataFormat',['studentService', dataFormatFilter])

My Filter factory and filter function.

    export function dataFormatFilter(studentService){
console.log(studentService); // Having access here
return dataFormatFunction; 
}
 
function dataFormatFunction(name){
// All the formatting logic

//Need properties from studentService in this function.
}

I am able to access the properties from studentService in dataFormatFilter(factory function). Is there a way to get it in dataFormatFunction.

All the solutions i have seen use dataFormatFunction inside of factory itself dataFormatFilter. But i cannot follows this way.

Thanks!

vawoh
  • 1
  • 1
  • I think it would help to understand what is restricting you from declaring `dataFormatFunction` within your filter factory. The problem you are running into is a fundamental concept around javascript closures. The only other thing I can think of would be chaining another factory method that returns your desired function, but that would be redundant. – Mark Clark Feb 09 '22 at 21:29
  • Thanks @MarkClark. The reason I can't move it into the function is because i am also using it as a utility function for formatting in other places. It has export which i didn't add in the question. – vawoh Feb 11 '22 at 02:42

1 Answers1

0

What it looks like you need to to is return an arrow function that will keep the closure of your filter function so you can use the dependencies without having to pass them around. I wrote this plunkr to demonstrate.

The critical part being:

const dataFormatFilter = function (studentService) {
  return (name) => {
    return myReusableFunction(studentService, name);
  }
}

app.filter('dataFormat',['studentService', dataFormatFilter]);

Note that the returned value for the function is an arrow function. This isn't the only way to achieve what you are attempting, but should be the simplest.

Mark Clark
  • 471
  • 4
  • 15