我正在使用本地化过滤器刷新问题.加载文件后,视图不会刷新.我已经尝试了$scope.$apply()和$filter(“localization”)(localizationService.text),两者都没有.
本地化服务:
angular .module("myApp") .factory("localizationService",function () { var service = { text: null,language: "en" }; return service; });
定位过滤器:
angular .module("myApp") .filter("localization",function(localizationService) { return function (value) { if (localizationService.text && localizationService.text.hasOwnProperty(value)) { return localizationService.text[value]; } return value; } });
$scope.$watch(function () { return $location.path(); },function () { var fileName = "../Localizations/" + $location.path().substring(1) + "/localization-" + localizationService.language + ".json"; $http.get(fileName).then(function (response) { localizationService.text = response.data; //$filter("localization")(localizationService.text); //$scope.$apply(); }); });
本地化en.json:
{ "test": "this is working !" }
HTML:
<div>{{'test' | localization}}</div>
这段代码写测试而不是这个工作!
我怎样才能解决这个问题 ?
从版本1.3.0-rc.2开始,过滤器默认为无状态.这意味着只有在左侧表达式发生更改时才会重新评估已过滤的表达式.
原文链接:/angularjs/141620.html你有这个:
<div>{{'test' | localization}}</div>
在这种情况下,测试显然永远不会改变,所以整个表达式只会被评估一次.
您需要将过滤器标记为有状态:
app.filter("localization",function(localizationService) { function localization(value) { if (localizationService.text && localizationService.text.hasOwnProperty(value)) { return localizationService.text[value]; } return value; } localization.$stateful = true; return localization; });