用字符串中的静态值替换角度表达式 [英] replace angular expressions with static values in a string
本文介绍了用字符串中的静态值替换角度表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在角度控制器中,我有:
In an angular controller I have:
var stringTemplate = "{{data.a}} - {{data.b}}";
var data = {a: "example1", b: "example2"};
是否可以用 data
中的静态值替换 stringTemplate
中的表达式.因此,在这种情况下,结果应为"example1-example2"
.
Is there a way to replace the expressions in stringTemplate
with static values from data
. So in this case the result should be "example1 - example2"
.
我需要将此存储在数据库中,并在 data
不可用时使用.
I need to store this in a database and use later when data
is not available.
数据
和 stringTemplate
中的值将更改.
推荐答案
您可以使用 ES6中引入的模板文字语法.
var data = {
a: "example1",
b: "example2"
};
var stringTemplate = `${data.a} - ${data.b}`;
console.log(stringTemplate);
ES5 :使用正则表达式
var data = {
a: "example1",
b: "example2"
};
var stringTemplate = "{{data.a}} - {{data.b}}";
stringTemplate = stringTemplate.replace(/\{{(.*?)}}/g, function($0, $1) {
return data[$1.split('.')[1]] || $0;
});
console.log(stringTemplate);
这篇关于用字符串中的静态值替换角度表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文