Monday, 26 September 2016

AngularJS filter to Translate input and replace variable separately afterwards into the translated input

Translate input and replace the variable afterwards on the string with variable placeholder ie. [variable].

First create AngularJs filter fiel called translate-input-var-and-replace.js and save with below content:
/* Translate input and replace the variable afterwards on the string with variable placeholder ie. [variable]. */
myapp.filter('translateInputWithVarReplace', ['$filter', function($filter) {
    return function(input, replaceVariable) {
        input = $filter('translate')(input);
        return input.replace(RegExp(/\[(.*?)\]/g), replaceVariable);
    };
}]);


Usage:
// The 'translated_string' should have the value containing the [variable] in the string. 
// translated_string = 'There will be [variable] people watching this movie.';

 var output = $filter('translateInputWithVarReplace')('translated_string', '545');

Expected Output:
There will be 545 people watching this movie.

No comments:

Post a Comment

Please post any queries and comments here.