robin robin - 4 years ago 103
AngularJS Question

Issue with angular translation in custom filter

I am trying to create a filter for showing the elapsed date and time in angular js and is working fine. Now I am trying to add translation to it but that time its showing the keys instead of the values.I think the issue is because the translation is not loaded while the filter is executing.

I am trying translation in the code like

if(hours){
result+= " "+hours+$translate.instant("elapsedFull.hours");
}
if(minutes){
result+= " "+minutes+$translate.instant("elapsedFull.minutes");
}
if(seconds){
result+= " "+seconds+$translate.instant("elapsedFull.seconds");
}


Please check the plunker link and let me know how can i fix the issue.

Plunker

Answer Source

Your filter should be a stateful filter like below:

var elapsedFull = function($translate,$timeout){
     function myFilter(date){
        var duration = Date.now() - date;
        var seconds = (duration / 1000) | 0;
        duration -= duration * 1000;
        var minutes = (seconds / 60) | 0;
        seconds -= minutes * 60
        var hours = (minutes / 60) | 0;
        minutes -= hours * 60;
        var days = (hours / 24) | 0;
        hours -= days * 24;
            var result="";
            if(days){
                result = days+"d";
            }
            if(hours){
                result+= " "+hours+$translate.instant("elapsedFull.hours");
            }
            if(minutes){
                result+= " "+minutes+$translate.instant("elapsedFull.minutes");
            }
            if(seconds){
                result+= " "+seconds+$translate.instant("elapsedFull.seconds");
            }
        return result;
    }
    myFilter.$stateful = true;
    return myFilter;
    }

AngularJS assumes that your filter function returns the same result if given the same arguments. Thus it caches the filtered results to avoid calling the filter. So, what if you wanted to compute the result of the filter asynchronously? The filter cannot return a promise, it must return some value, at least an undefined. The best it can hope is to recompute the value again in the future and return something else. Such filters are called stateful, and they require property $stateful to be set to true on the returned function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download