在 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 中被破坏?
Thanks!
在 Angular 1.3 中,过滤发生了变化,因此它们不再是“有状态的”。您可以在这个问题中看到更多信息:AngularJS 中的状态过滤是什么? https://stackoverflow.com/questions/25877704/what-is-a-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;
});
或者以其他方式实现您的过滤器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)