1

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).

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

That's awesome, wasn't aware about that context thing putted instead of $scope +1
It seems to nullify nullify the values it can't find (e.g. if {{Some}} doesn't exist it replaces it with an empty string). Is it possible to disable this behavior? The reason is that the same template needs to be interpolated with several models/json objects sequentially
@AnthonyHunt Merge all the objects together first, then interpolate.
I can't do that because a part of the template must be parsed when the client "sees" it and another part of the template when it takes an action. Isn't possible to instruct interpolate to "ignore" the variables not found?
@AnthonyHunt What do you mean "ignore"? Keep the interpolation expressions intact? In that case, no, you can't, but why would you ever want a user to see the expression with the interpolation expressions still in the string?
|

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.