Filter do not refresh
Asked Answered
W

1

10

I'm having refresh issues with a localization filter. When the file is loaded, the view do not get refreshed. I've tried $scope.$apply() and $filter("localization")(localizationService.text), neither is working.

localizationService :

angular
    .module("myApp")
    .factory("localizationService", function () {
        var service = {
            text: null,
            language: "en"
        };

        return service;
    });

localization filter :

angular
    .module("myApp")
    .filter("localization", function(localizationService) {
        return function (value) {
            if (localizationService.text && localizationService.text.hasOwnProperty(value)) {
                return localizationService.text[value];
            }
            return value;
        }
    });

controller refreshing automatically the file to use :

    $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();
        });
    });

localization-en.json :

{
  "test": "this is working !"
}

HTML :

<div>{{'test' | localization}}</div>

This code writes test instead of this is working !.

How can I fix this ?

Whoa answered 17/11, 2015 at 8:15 Comment(1)
Looks like the filter is evaluated only once before the file is loaded... I don't get why it is not re-evaluating the filter afterwards. While a $scope.$apply(); says : $digest already in progress...Whoa
D
28

Ever since version 1.3.0-rc.2, filters are by default stateless. This means that the filtered expression will only be reevaluated if the left-hand-side expression changes.

You have this:

<div>{{'test' | localization}}</div>

test will obviously never change in this case, so the entire expression will only be evaluated once.

You need to flag the filter as stateful:

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;
});

Demo: http://plnkr.co/edit/YIzmH3lR9350McprusAA?p=preview

Decosta answered 17/11, 2015 at 11:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.