Warlock
Warlock

Reputation: 7471

How to interpolate string in Angular

I have an angular web application, so I would like to use angular also for string interpolations. For example, I would like to make some replacements in myTemplate:

var myTemplate = "Make something awesome with a = '{{scope.a}}' and b = '{{scope.b}}'.";
var scope = {
  a: 1,
  b: 2
};

I know how to do this with underscore.js:

_.template(myTemplate)(scope);

I'm wondering if it is possible in angular?

Upvotes: 0

Views: 165

Answers (2)

dfsq
dfsq

Reputation: 193261

Use $interpolate service:

var myTemplate = "Make something awesome with a = '{{a}}' and b = '{{b}}'.";
var scope = {
    a: 1,
    b: 2
};

$interpolate(myTemplate)(scope); // "Make something awesome with a = '1' and b = '2'."

Only with above scope object structure, you should use {{a}} instead of {{scope.a}}.

Demo: http://plnkr.co/edit/aoaeWekhkLP5k7NR2RWB?p=preview

Upvotes: 3

ryeballar
ryeballar

Reputation: 30098

Yes you can make use of angular's $interpolate service

var myTemplate = "Make something awesome with a = '{{a}}' and b = '{{b}}'.";
var fn = $interpolate(myTemplate);

var scope = {
  a: 1,
  b: 2
};


// Make something awesome with a = '1' and b = '2'.
fn(scope);

Upvotes: 1

Related Questions