简体   繁体   English

从角度范围变量有条件地信任html

[英]conditionally trust html from angular scope variable

I have an html snippet as follows: 我有一个html片段,如下所示:

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

In order to bind to html, I need to do the following: 为了绑定到html,我需要执行以下操作:

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

Ideally, I want to be able to set a flag to trust $scope.message as html... So my options are to use an ng-if with duplicate code, but this is not ideal because I would like this to the same id for both message elements. 理想情况下,我希望能够设置一个标志来将$ scope.message信任为html ...所以我的选择是将ng-if与重复代码一起使用,但这并不理想,因为我希望对同一个id这两个消息元素。 I was also looking into taking advantage of ng-attr, but don't believe this will work. 我也一直在考虑利用ng-attr,但不相信这会起作用。

Is there a way I can conditionally add "ng-bind-html" and "ng-bind", so evaluate a flag and remove the undesired attribute? 有没有一种方法可以有条件地添加“ ng-bind-html”和“ ng-bind”,因此评估标志并删除不希望的属性? I am new to angularjs. 我是angularjs的新手。

You could make use of the $sanitize service and a function to either return just your message or return your message wrapped in $sanitize . 您可以利用$ sanitize服务和一个函数来返回仅邮件或返回包装在$sanitize邮件。 Then you could just use ng-bind 然后你可以使用ng-bind

An example 一个例子

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

In your controller 在您的控制器中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM