如何根据函数 returns 呈现数字或 HTML 元素?
How to render either a number or a HTML element depending on what a function returns?
我有一个函数 getScore()
,它 returns 一个数字或 null。然后我在我的 html 文件中这样调用它:
<span>{{ getScore(assessmentRequest) }}</span>
现在我想更改它,以便在返回数字时呈现数字,或者在 returns 为空时呈现图标。我试过这样的东西,但它只是 returns 一个字符串而不是实际的 HTML 元素:
<span>{{ getScore(assessmentRequest) ? getScore(assessmentRequest) : '<i class="icon ion-checkmark"></i>' }}</span>
在那种情况下,我将如何呈现实际的 HTML 元素?
一种方法是使用 ngIf
对于AngularJS:
<span ng-If="assessmentRequestValue">{{ assessmentRequestValue }}</span>
<span ng-If="!assessmentRequestValue"><i class="icon ion-checkmark"></i></span>
对于 Angular2+
<span *ngIf="assessmentRequestValue">{{ assessmentRequestValue }}</span>
<span *ngIf="!assessmentRequestValue"><i class="icon ion-checkmark"></i></span>
对于两者,Try not to use function calls in angular template expressions 在控制器中的某处使用 getScore(assessmentRequest) 来设置 assessmentRequestValue
如何使用 ng-bind-html 指令。如原始文档所述
Evaluates the expression and inserts the resulting HTML into the element in a secure way
EG
<span ng-bind-html="getScore(assessmentRequest) ? getScore(assessmentRequest) : '<i class="icon ion-checkmark"></i>' "></span>
我有一个函数 getScore()
,它 returns 一个数字或 null。然后我在我的 html 文件中这样调用它:
<span>{{ getScore(assessmentRequest) }}</span>
现在我想更改它,以便在返回数字时呈现数字,或者在 returns 为空时呈现图标。我试过这样的东西,但它只是 returns 一个字符串而不是实际的 HTML 元素:
<span>{{ getScore(assessmentRequest) ? getScore(assessmentRequest) : '<i class="icon ion-checkmark"></i>' }}</span>
在那种情况下,我将如何呈现实际的 HTML 元素?
一种方法是使用 ngIf
对于AngularJS:
<span ng-If="assessmentRequestValue">{{ assessmentRequestValue }}</span>
<span ng-If="!assessmentRequestValue"><i class="icon ion-checkmark"></i></span>
对于 Angular2+
<span *ngIf="assessmentRequestValue">{{ assessmentRequestValue }}</span>
<span *ngIf="!assessmentRequestValue"><i class="icon ion-checkmark"></i></span>
对于两者,Try not to use function calls in angular template expressions 在控制器中的某处使用 getScore(assessmentRequest) 来设置 assessmentRequestValue
如何使用 ng-bind-html 指令。如原始文档所述
Evaluates the expression and inserts the resulting HTML into the element in a secure way
EG
<span ng-bind-html="getScore(assessmentRequest) ? getScore(assessmentRequest) : '<i class="icon ion-checkmark"></i>' "></span>