angularjs如何在html中转义“$ {variable}”?

时间:2017-03-29 06:42:05

标签: javascript html angularjs html-escape-characters

我想在div元素中显示类似$ {date}的字符串:

<div>please use the ${date} as the substitute tag to the name</div>

内容将显示如下:

please use the ${date} as the substitute tag to the name.

但浏览器将$ {date}视为javascript变量,那么如何在angularjs中转义$ {date}字符串?

5 个答案:

答案 0 :(得分:1)

您可以使用&#36;代替在代码中编写$。它是美元符号的HTML表示,应该防止该表达式被识别为变量。

<div>please use the &#36;{date} as the substitute tag to the name</div>

您可以找到这些代码的完整列表at the W3 Character Entity Reference.

答案 1 :(得分:0)

在控制器中创建一个方法,将字符串交回模板:

specialText() {
  return '${date}';
}

然后在你的模板中:

<div>please use the {{vm.specialText()}} as the substitute tag to the name</div>

答案 2 :(得分:0)

JS中的

$sce添加为DI

$scope.stringVar = $sce.trustAsHtml('please use the ${date} as the substitute tag to the name');

HTML中的

<div ng-bind-html="stringVar"></div>

答案 3 :(得分:0)

感谢所有答案,我已经以优雅的方式解决了这个问题。

我将字符串${date}替换为{{"\${date}"}},它可以正常工作。这意味着浏览器将"\${date}"视为angularjs表达式,该表达式引用常量字符串值。

顺便说一下,$是字符串中的特殊字符,我们应该在它之前添加一个转义字符\

答案 4 :(得分:0)

没有转义字符的轻量级解决方法: 拆分表达式并将内部部分包裹在span中,如下所示。

<div>please use the ${<span>date</span>} as the substitute tag to the name</div>