如何让一个 AngularJS 表达式不显示任何内容?



假设我有以下 HTML:

<p>{{ booleanVariable ? "The variable is true!" : null }}</p>

如果booleanVariable为 false,则表达式应为空,并且不应呈现<p></p>。但是,它只是将"null"打印到<p>标签中,就好像我刚刚键入<p>null</p>一样。

我如何让表达式不渲染任何内容?

使用undefined而不是null

<p>{{ booleanVariable ? "The variable is true!" : undefined }}</p>

更简单的解决方案是ngShow

<p ng-show="booleanVariable">The variable is true!</p>

空字符串是有意义的。

<p>{{ booleanVariable ? "The variable is true!" : '' }}</p>

最好的解决方案是使用

<p ng-if="booleanVariable">The variable is true!</p>

ng-show在 DOM 中会有<p>,但如果你使用ng-if<p>它只是隐藏的,也不会在 DOM 中

最新更新