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.

Merging two or more JavaScript Objects using AngularJS

Please use below steps to merge two or more JavaScript Objects using AngularJS

// Object one
var jsObjectA = {title:'Buddha is born in Nepal', famous:'Gautum Buddha', country:'Nepal', district:'Bhirawa'};

// Object two
var jsObjectB = {religion:'Buddhism', zone:'Lumbini', district:'Kapilvastu'};

// Merging above two objects
var mergeObject = angular.extend({}, jsObjectA, jsObjectB); 

Expected Output:
{title:'Buddha is born in Nepal', famous:'Gautum Buddha', country:'Nepal', religion:'Buddhism', zone:'Lumbini', district:'Kapilvastu'};