Javascript angularjs如何逃脱“${variable}”;在html中?
我想向div元素显示类似${date}的字符串:Javascript angularjs如何逃脱“${variable}”;在html中?,javascript,html,angularjs,html-escape-characters,Javascript,Html,Angularjs,Html Escape Characters,我想向div元素显示类似${date}的字符串: <div>please use the ${date} as the substitute tag to the name</div> 但是浏览器将${date}视为javascript变量,因此如何在angularjs中转义${date}字符串?在控制器中创建一个方法,将字符串交回模板: specialText() { return '${date}'; } <div>please use the {
<div>please use the ${date} as the substitute tag to the name</div>
但是浏览器将${date}视为javascript变量,因此如何在angularjs中转义${date}字符串?在控制器中创建一个方法,将字符串交回模板:
specialText() {
return '${date}';
}
<div>please use the {{vm.specialText()}} as the substitute tag to the name</div>
然后在模板中:
specialText() {
return '${date}';
}
<div>please use the {{vm.specialText()}} as the substitute tag to the name</div>
请使用{{vm.specialText()}}作为名称的替换标记
在JS中添加$sce
作为DI
$scope.stringVar=$sce.trustAsHtml('请使用${date}作为名称的替换标记')代码>
在HTML中
<div ng-bind-html="stringVar"></div>
谢谢你的回答,我已经用一种优雅的方式解决了这个问题
我将字符串${date}
替换为{{“\${date}}}
,它就可以工作了。这意味着浏览器将“\${date}”
视为引用常量字符串值的angularjs表达式
顺便说一句,$
是字符串中的一个特殊字符,我们应该在它前面添加转义字符。一个没有转义字符的轻量级解决方法:
拆分表达式并在span中包裹内部部分,如下所示
<div>please use the ${<span>date</span>} as the substitute tag to the name</div>
请使用${date}作为名称的替换标记
您可以使用&36代码>而不是在代码中写入$。它是美元符号的HTML表示形式,应防止将该表达式识别为变量
<div>please use the ${date} as the substitute tag to the name</div>
请使用$;{date}作为名称的替换标记
您可以找到这些代码的完整列表您可以查看服务。或者您可以使用
或
标记来代替
,只要您不更改开始和结束插值标记,您就不应该对该字符串有任何问题,因为该字符串不被视为表达式。我尝试了或标记,但它不起作用。$sce服务可能解决我的问题,“但这似乎是多余的。”Nicolaeliu,我使用了另一个开始和结束插值标记,因为我将它与django一起使用。