Anthony Hunt
Anthony Hunt

Reputation: 1610

How to compile arbitrary templates/models using angularjs?

I have a web service which returns a template e.g.

Hello {{Name}}, Today is {{Yesterday}}

Then I have another website which returns a json object

{
  "Name": "Mr. Been",
  "Yesterday": "a nice day",
  "otherdata": "unknown"
}

Is it possible to replace the keys from the template with the data from the json object?

The template and web service data is totally dynamic (unknown).

Upvotes: 1

Views: 71

Answers (1)

Alexis King
Alexis King

Reputation: 43852

Yes, you can use the $interpolate service. It converts an string with potential angular interpolation expressions into a function that accepts a scope object and returns the interpolated string.

You would use it like this:

// get the template and data to interpolate however is necessary
var template = getTemplate();
var locals = getLocals();

// perform interpolation
var result = $interpolate(template)(locals);

There are some other options you can pass to customize how the $interpolate function works, so take a look at the documentation for more details.

Upvotes: 1

Related Questions