如何在Angular中插入字符串

时间:2014-09-17 16:21:49

标签: javascript angularjs

我有一个角度Web应用程序,所以我想使用angular也用于字符串插值。例如,我想在myTemplate中进行一些替换:

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

我知道如何使用underscore.js执行此操作:

_.template(myTemplate)(scope);

我想知道角度是否可行?

2 个答案:

答案 0 :(得分:3)

使用$ interpolate服务:

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'."

仅限上述scope对象结构,您应使用{{a}}代替{{scope.a}}

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

答案 1 :(得分:1)

是的,您可以使用angular $interpolate服务

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