admin管理员组

文章数量:1422254

I want to show a string like ${date} to the div element:

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

the content will be display like:

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

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

I want to show a string like ${date} to the div element:

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

the content will be display like:

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

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

Share Improve this question edited Mar 29, 2017 at 6:47 Bruce asked Mar 29, 2017 at 6:42 BruceBruce 731 silver badge10 bronze badges 4
  • 2 you can check for $sce services. or you can use <code> or <pre> tag instead of <div> – xkeshav Commented Mar 29, 2017 at 6:46
  • As long as you don't change the start and end interpolation tags, you shouldn't have any problems with that string, that not being considered an expression. – Nicolae Olariu Commented Mar 29, 2017 at 6:53
  • I try the <code> or <pre> tag but it doesn't work.$sce services maybe could solve my problem, but it seems redundant. – Bruce Commented Mar 29, 2017 at 7:08
  • @NicolaeOlariu, I use another start and end interpolation tags because I use it with django. – Bruce Commented Mar 29, 2017 at 7:30
Add a ment  | 

5 Answers 5

Reset to default 1

Make a method in your controller to hand the string back to the template:

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

Then in your template:

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

in JS add $sce as DI

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

in HTML

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

You could use &#36; instead of writing $ in your code. It is the HTML representation for the dollar sign, and should prevent that expression from being recognized as a variable.

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

You can find a full list of these codes at the W3 Character Entity Reference.

Thanks for all the answers, I have resolve the problem in an elegant way.

I replace the string ${date} with {{"\${date}"}} and it works. It means that the browser regards the "\${date}" as a angularjs expression which is referenced to the constant string value.

By the way, $ is a special character in string, we should add an escape character \ before it.

A light-weight workaround without escape characters: Split your expression and wrap inner part in span, as below.

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

本文标签: javascriptangularjs How to escape “variable” in htmlStack Overflow