2

I am trying to replace string words which are enclosed in $ with values of JSON.

For example:

I have json.

$scope.data = {
  name: "Some Name",
  user: "User Name",
  designation: "Designation",
  fullName:"User Full Name"
}

And I have String:

$scope.str="User name of $user$ is $name$ and designation is  $designation$";

Is there any angular method from which I can directly replace variables from this string?

I tried using loop through keys and verifying, It is working but there are more than 100 keys in json and there might be less than 20 keys will get used in string.

I am expecting a better approach which improve performance.

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

It's not pure angular but if you by change using Lodash (which is utility library taking part of many projects) there is template method. And you can easily configure a placeholder syntax

_.templateSettings.interpolate = /\$([\s\S]+?)\$/g;
var compiled = _.template('User name of $user$...');
compiled({ 'user': 'Foo' });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.