4

I'm trying to make simple multi-language website. I have a small controller just to be able to change current language in root scope:

 app.controller('Ctrl', function($scope, $rootScope) { $rootScope.currentLang = 'en_US'; $scope.switchLang = function(){ if($rootScope.currentLang ==='en_US'){ $rootScope.currentLang = 'cs_CS'; } else { $rootScope.currentLang = 'en_US'; } } }); 

And I want to store my data in filter:

 app.filter('ci18n', function($rootScope){ return function(id_text){ var translations = { 'en_US' : { 'GREETING' : 'Hi' }, 'cs_CS' : { 'GREETING' : 'Cau' } }; return translations[$rootScope.currentLang][id_text]; }; }); 

Problem is that my website does't change with rootScope change. I need an idea how to solve it better or how to trigger filter again to change my texts.

Here is how I use the filter

<p>greet: {{'GREETING' | ci18n}}</p> 
3
  • Did you try with $scope.$apply();? Commented Jun 26, 2015 at 13:11
  • I tried that inside of switchLang() function with no change. Commented Jun 26, 2015 at 13:13
  • Is cs_CS a C# locale? Or did you mean cs_CZ? Commented Jun 17, 2016 at 16:08

1 Answer 1

14

Starting from Angular 1.3, filters are assumed to be stateless in order to speed things up in the common case. That means Anguar won't re-evaluate your filter if its input has not changed. Angular has no idea that you're also reading $rootScope.currentLang within the filter implementation, so it doesn't know that the filter needs to be re-evaluated if currentLang changes.

The solution is to mark your filter as stateful explicitly:

 app.filter('ci18n', function($rootScope){ var filter = function(id_text){ var translations = { 'en_US' : { 'GREETING' : 'Hi' }, 'cs_CS' : { 'GREETING' : 'Cau' } }; return translations[$rootScope.currentLang][id_text]; }; filter.$stateful = true; // <-- the magic line return filter; }); 

Of course this does come with a performance penalty, but since your filter is just a map lookup, that shouldn't have much of an impact.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for perfectly clear answer, worked great.
@JanOmacka just a suggestion. Do accept the answer if it solves/addresses your issue(s)!
Sorry, forgot to hit the button, thanks for the remind.
Upgraded angular from 1.2 to 1.4 and lost the ability to change locale dynamically for some of my custom filters, $stateful really is the magic line here! Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.