2

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?

4
  • 2
    you can check for $sce services. or you can use <code> or <pre> tag instead of <div> 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. 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. Commented Mar 29, 2017 at 7:08
  • @NicolaeOlariu, I use another start and end interpolation tags because I use it with django. Commented Mar 29, 2017 at 7:30

5 Answers 5

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

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.

Comments

0

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.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.