Jan*_*cka 4 javascript angularjs angularjs-scope angularjs-filter angularjs-ng-click
我正在尝试制作简单的多语言网站.我有一个小控制器只是为了能够更改根范围中的当前语言:
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';
}
}
});
Run Code Online (Sandbox Code Playgroud)
我想将我的数据存储在过滤器中:
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];
};
});
Run Code Online (Sandbox Code Playgroud)
问题是我的网站不会随rootScope的变化而改变.我需要一个想法如何更好地解决它或如何再次触发过滤器来改变我的文本.
这是我如何使用过滤器
<p>greet: {{'GREETING' | ci18n}}</p>
Run Code Online (Sandbox Code Playgroud)
Tho*_*mas 14
从Angular 1.3开始,假设过滤器是无状态的,以便在常见情况下加快速度.这意味着如果输入没有改变,Anguar将不会重新评估你的过滤器.Angular不知道你也在$rootScope.currentLang
过滤器实现中读取,因此它不知道如果currentLang
更改需要重新评估过滤器.
解决方案是将您的过滤器明确标记为有状态:
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;
});
Run Code Online (Sandbox Code Playgroud)
当然,这确实会带来性能损失,但由于您的过滤器只是一个地图查找,因此不会产生太大影响.