如何在 Angularjs 中的字符串插值中获得换行符 [英] How to get line break within string interpolation in Angularjs
问题描述
所以我正在尝试做一些非常简单的事情,但我被卡住了.我有一个 String
变量,在该变量中我想设置换行符,以便文本的某些部分转到新行.
So I'm trying to do something very simple and I'm stuck. I have a String
variable and within that variable I Wanna set line break so certain part of the text goes to new line.
我尝试过的:
title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";
我尝试了很多变体,但都不起作用.我是不是很愚蠢,遗漏了一些非常明显的东西?
I have tried many variations but its just not working. Am I being stupid and missing something very obvious?
不是重复的,因为我已经尝试了 <br/>
但它没有用.
Not a duplicate as I have tried the <br/>
and it has not worked.
更新:
该变量正在浏览器 HTML 中打印,就像这样 {{title}}
The variable is being printed in the browser HTML like so {{title}}
推荐答案
这里有两个明显有效的版本...
Here are two demonstrably working versions...
解决方案一...如果您希望在 HTML 中尊重换行符...(使用反引号字符串,或使用 'My \ntitle'
...
Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with 'My \ntitle'
...
document.getElementById('example').innerHTML = `My
title`;
h1 {
white-space: pre;
}
<h1 id="example">
</h1>
角度版本:
<h1 style="white-space: pre;">{{title}}</h1>
HTML 中断
解决方案二...你想使用HTML...
HTML Break
Solution two... you want to use HTML...
document.getElementById('example').innerHTML = 'My<br />title';
<h1 id="example">
</h1>
如果您想在绑定期间允许 HTML,请使用 ng-bind-html.
Use ng-bind-html if you want to allow HTML during binding.
这篇关于如何在 Angularjs 中的字符串插值中获得换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!