apple_92
apple_92

Reputation: 263

How do I call a controller function from inside a custom filter?

I have a function in controller like this.

cl.translateCall = function () {
$http.get(`${API_URL}/langChange/` + selectedLanguage).
then(function onSuccess(response) {
      input = response.data; 
      console.log(input)
}).
  catch(function onError(response) {
  console.log(response)
});   
 }

I have a custom filter in module like this

   .filter('languageTranslate',['$http', function($http) {  

   return function(input) {
    if(selectedLanguage != null){

    /*want to call controller function*/

      }else{   
            return input;  
      } 
  }


}]);

How do I call the above controller function inside this Angular JS custom filter? I am totally new to Angular JS.

Upvotes: 0

Views: 488

Answers (1)

davidkonrad
davidkonrad

Reputation: 85528

Well, you can pass the scope to the filter. I dont know how you use the code above, but if you theoretically have :

{{ someVar | languageTranslate }}

Then you can pass the current scope by adding :this

{{ someVar | languageTranslate:this }} 

and call a scope method like this

return function(input, scope) {
  if (scope.selectedLanguage != null) {
    scope.functionName()
  } else {   
    return input 
  } 
}

Upvotes: 1

Related Questions