【问题标题】:AngularJS v1.3 breaks translations filterAngularJS v1.3 打破了翻译过滤器
【发布时间】:2015-01-07 01:06:38
【问题描述】:

在 Angular v1.2 中,我使用以下代码在应用程序中提供本地化字符串:

var i18n = angular.module('i18n', []);

i18n.service('i18n', function ($http, $timeout) {
    /**
        A dictionary of translations keyed on culture
    */
    this.translations = {},

    /**
        The current culture
    */
    this.currentCulture = null,

    /**
        Sets the current culture, loading the associated translations file if not already loaded
    */
    this.setCurrentCulture = function (culture) {
        var self = this;
        if (self.translations[culture]) {
            $timeout(function () {
                self.currentCulture = culture;
            });
        } else {
            $http({ method: 'GET', url: 'i18n/' + culture + '/translations.json?' + Date.now() })
                .success(function (data) {
                    // $timeout is used here to defer the $scope update to the next $digest cycle
                    $timeout(function () {
                        self.translations[culture] = data;
                        self.currentCulture = culture;
                    });
                }); 
        }
    };

    this.getTranslation = function (key) {
        if (this.currentCulture) {
            return this.translations[this.currentCulture][key] || key;
        } else {
            return key;
        }
    },

    // Initialize the default culture
    this.setCurrentCulture(config.defaultCulture);
});

i18n.filter('i18n', function (i18n) {
    return function (key) {
        return i18n.getTranslation(key);
    };
});

然后在模板中按如下方式使用:

<p>{{ 'HelloWorld' | i18n }}</p>

出于某种我无法理解的原因,升级到 AngularJS 的 v1.3 已经破坏了这个功能。 $timeout 没有触发摘要循环,或者过滤器没有更新。我可以看到 $timeout 代码正在运行,但过滤器代码从未被命中。

任何想法为什么这可能会在 v1.3 中被破坏?

谢谢!

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    在 Angular 1.3 中,过滤已更改,因此它们不再是“有状态的”。您可以在此问题中查看更多信息:What is stateful filtering in AngularJS?

    最终结果是过滤器将不再重新评估,除非输入发生变化。要解决此问题,您可以添加以下行:

    i18n.filter('i18n', function (i18n) {
        var filter = function (key) {
            return i18n.getTranslation(key);
        };
        filter.$stateful = true;    ///add this line
        return filter;
    });
    

    或者以其他方式实现您的过滤器。

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 2015-06-03
      • 2020-12-29
      相关资源
      最近更新 更多