Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter do not refresh

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 ?

like image 739
Elfayer Avatar asked Nov 17 '15 08:11

Elfayer


1 Answers

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

like image 69
tasseKATT Avatar answered Sep 24 '22 10:09

tasseKATT