简体   繁体   English

AngularJS - 如何在ng-click上触发过滤器

[英]AngularJS - how to trigger filter on ng-click

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. 问题是我的网站不会随rootScope的变化而改变。 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>

Starting from Angular 1.3, filters are assumed to be stateless in order to speed things up in the common case. 从Angular 1.3开始, 假设过滤器是无状态的 ,以便在常见情况下加快速度。 That means Anguar won't re-evaluate your filter if its input has not changed. 这意味着如果输入没有改变,Anguar将不会重新评估你的过滤器。 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. Angular不知道您还在过滤器实现中读取$rootScope.currentLang ,因此如果currentLang发生更改,它不知道需要重新评估过滤器。

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. 当然,这确实会带来性能损失,但由于您的过滤器只是一个地图查找,因此不会产生太大影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM