1). String.prototype.replace. It actually makes sense to do it in pure Javascript with String.prototype.replace method, it's going to be more effective. For example like this:
$scope = {};
$scope.data = {
name: "Some Name",
user: "User Name",
designation: "Designation",
fullName: "User Full Name"
};
$scope.str = "User name of $user$ is $name$ and designation is $designation$";
$scope.str = $scope.str.replace(/\$(\w+)\$/g, function(a, b) {
return typeof $scope.data[b] !== 'undefined' ? $scope.data[b] : '';
});
alert($scope.str);
If you plan to use this "micro-templater" more then once, consider to move it into separate service.
2). Angular $interpolate. You can also make use of interpolate service if you can change placeholder syntax to {{name}}:
app.controller('MainCtrl', function($scope, $interpolate) {
$scope.data = {
name: "Some Name",
user: "User Name",
designation: "Designation",
fullName: "User Full Name"
};
$scope.str = "User name of {{user}} is {{name}} and designation is {{designation}}";
$scope.str = $interpolate($scope.str)($scope.data);
});
Once again, you can build simple template service on top of it:
app.service('template', function($interpolate) {
return function(str, data) {
return $interpolate(str)(data);
};
});
and use it in controller like:
$scope.str = template($scope.str, $scope.data);