6

I'm loading up data from the server via ajax requests. The JSON file has configurations for popups in the site.

popupData: {
   data:{ var_one: "hello", var_two: "world"},
   template: "the <b>{{var_two}}</b> say's {{var_one}}"
}

The variable names and template will be different for every occurrence of the popup.

How can I get this string interpolated with the data that comes with it? I need to pass the pre-built string to a component to be viewed using [innerHTML].

4
  • I may be missing something, but wouldn't a template literal help here? template `the <b>${var_two}</b> say's ${var_one}` Commented Apr 10, 2017 at 16:17
  • You can't store templates in JSON Commented Apr 10, 2017 at 16:39
  • You can do this with good 'ol selectors. I have a popup component that is just a shell into which I load html fragments (I pass a value in the router url fragment, read it in the popup component, and load the indicated html page/fragment as the content). If I need to load variable data into that fragment, I just use a selector: querySelector ( '#popup_some_style_or_id_selector' ).innerHTML .= [whatever value you want]. In Angular 1, that loaded fragment could use ng-include and access the vals in the controller. that doesn't go in Ang 2/4. It's one thing that Angular still has to iron out. Commented Apr 10, 2017 at 17:03
  • @MikeRoberts you can indeed store template literals. They are evaluated to the json string Commented Apr 10, 2017 at 17:17

1 Answer 1

3

Somewhere after the data was received:

const popupString = popupData.template.replace(
  /{{\s?([^{}\s]*)\s?}}/g,
  (substring, parsedKey) => {
    const replacer = popupData.data[parsedKey];
    return typeof replacer !== 'undefined' ? replacer : substring;
  }
);

It should equal the <b>world</b> says Hello in your example.

Please note that this code comes from robisim74’s angular-l10n (MIT license).

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

1 Comment

It works! Although I was hoping for something more built-in to angular. My other option was to use moustache or handlebars templates. It just seems weird you have to roll your own interpolation inside angular.

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.