Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ng bind html不适用于输入标记_Javascript_Angularjs_Ng Bind Html_Ng Bind_Ngsanitize - Fatal编程技术网

Javascript ng bind html不适用于输入标记

Javascript ng bind html不适用于输入标记,javascript,angularjs,ng-bind-html,ng-bind,ngsanitize,Javascript,Angularjs,Ng Bind Html,Ng Bind,Ngsanitize,我试图在一个范围变量中存储一个HTML,然后在模板视图中使用它。当我在angular阅读如何执行此操作时,我遇到了ngbindhtml。在这方面,我注意到当我用,等绑定html标记时。。它起作用了。但是我无法向它添加标记 意思是,这是有效的: $scope.myHtml = '<strong>This is <a hreaf="#">Something</a></strong>'; $scope.myHtml = '<input type=

我试图在一个范围变量中存储一个HTML,然后在模板视图中使用它。当我在angular阅读如何执行此操作时,我遇到了
ngbindhtml
。在这方面,我注意到当我用
等绑定html标记时。。它起作用了。但是我无法向它添加
标记

意思是,这是有效的:

$scope.myHtml = '<strong>This is <a hreaf="#">Something</a></strong>';
$scope.myHtml = '<input type="text" />';
$scope.myHtml='这是一件事;
模板:

<p ng-bind-html="myHtml"> </p>
<p ng-bind-html="myHtml"> </p>

但这不起作用:

$scope.myHtml = '<strong>This is <a hreaf="#">Something</a></strong>';
$scope.myHtml = '<input type="text" />';
$scope.myHtml='';
模板:

<p ng-bind-html="myHtml"> </p>
<p ng-bind-html="myHtml"> </p>

以上只是一个简化示例,仅供演示之用。我的问题是:

1)标记不适用于ng bind html指令吗?


2)如果没有,我如何用html绑定输入标记,以便将其插入视图中?

我会将您插入的内容保留在其自己的模板中,并使用ng include()

具有包含以下内容的角度模板(template.html):

<strong>This is <a href="#">Something</a></strong>
这是
你可以把它包括在内

<p ng-include="template.html"></p>

这会导致类似的结果

<p ng-include="template.html"><span class="ng-scope"><strong>This is <a href="#">Something</a></strong></span></p>

这是


Angular使用ng bind HTML选择性地清理某些HTML标记

因此,如果需要所有标记,则应使用ng bind html unsafe

但是要小心XSS攻击

顺便提一下
遵循@Ed Hinchliffe的建议要好得多

您将获得$sce:不安全错误

这意味着您应该使用
ng bind html unsafe
,但angularjs的较新版本不再包含此指令,因此您应该像这样使用$
sce.trustAsHtml()

$scope.trustedInputHtml = $sce.trustAsHtml('<input type="text" />');
$scope.trustedInputHtml=$sce.trustAsHtml(“”);
但这种方法无法将作用域变量绑定到html,所以最好的方法是编写一个指令,该指令可以替换为
ng bind html unsafe


这里是为$sce和指令示例工作的…

它可能不工作,html在插入之前经过清理,我猜输入被认为是不安全的。你为什么要这么做。它看起来很凌乱,我相信有更好的方法使用模板或指令。我实际上是在一个复杂的指令中使用它,该指令基于属性选择构造html标记进行输入,然后在通过
$http get
获取的模板中使用它。您是否在中使用
compile
函数那个指令?是的。。它会在最后编译它。好的。如果没有,我仍然认为您可以通过在指令的指令定义对象中声明compile函数并在其中修改模板来实现这一点,而不必使用
ng bind html
或类似的方法。我认为
ng bind html不安全
在最新版本中不再工作。我用1.2.16版本检查了它,并且我喜欢它!我要测试一下你的工作样品。谢谢你给我这个很棒的例子。一旦我在我的应用程序中测试了一个更新,我会回来的。@blackops\u如果你不想为此创建自定义指令,程序员也可以查看我的更新……谢谢你的回答。在
ng bind html
之前使用
$sce.trustAsHtml()
确实有效。然而,在采纳了你的建议以及EdHinchliffe和Whisher的建议之后,我最终还是采用了指令方法。更好的是,我甚至不需要使用消毒模块来让它工作。非常感谢你。今天我花了好几个小时才找到这个!我很高兴有一个干净的方法来实现这一点。你上面的Plunker样品帮了大忙。非常感谢!:)@wickY26指令就是这里的
编译
指令:重命名^^Wow!这正是我想要解决的问题:。非常感谢你!