有条件地信任angular scope变量中的html

conditionally trust html from angular scope variable

本文关键字:html 变量 scope 信任 angular 有条件      更新时间:2023-09-26

我有一个html片段如下:

<span id="notification"> {{ message }} </span>

为了绑定到html,我需要做以下操作:

<span id="notification" ng-bind-html="message"></span>

理想情况下,我希望能够设置一个标志,将$scope.message信任为html。。。因此,我的选择是使用带有重复代码的ng-if,但这并不理想,因为我希望这两个消息元素的id相同。我也在考虑利用ng attr,但不相信这会奏效。

有没有一种方法可以有条件地添加"ng-bind-html"answers"ng-bond",从而评估一个标志并删除不需要的属性?我是angularjs的新手。

您可以使用$sance服务和一个函数来只返回您的消息或返回用$sanitize包装的消息。然后你可以使用ng-bind

示例

<span id="notification" ng-bind="notificationCtrl.getMessage(message, true)"></span>

在您的控制器中

this.getMessage = function(msg, sanitize) {
   if (sanitize) return $sanitize(msg)
   return msg
}