问题
I am trying to store a HTML inside a scope variable and then use it in template view. When I was reading how to do this in angular, I came across ng-bind-html
. In that I've noticed that when I bind html tags with <a>
, <strong>
, etc.. it works. But I am unable to add <input>
tags to it.
Meaning, this works:
$scope.myHtml = '<strong>This is <a hreaf="#">Something</a></strong>';
Template:
<p ng-bind-html="myHtml"> </p>
But this doesnt work:
$scope.myHtml = '<input type="text" />';
Template:
<p ng-bind-html="myHtml"> </p>
The above is just a simplified sample for demonstration purpose only. My question is:
1) Does tags not work with ng-bind-html directive?
2) If not, how can I html bind a input tag so I can insert it inside the view?
回答1:
you are getting $sce:unsafe error...
this means you should use ng-bind-html-unsafe
but newer version of angularjs does not include this directive anymore so you shoud use $sce.trustAsHtml()
like this...
$scope.trustedInputHtml = $sce.trustAsHtml('<input type="text" />');
but this way you cannot bind scope variables to your html so best way is writing a directive which can be replace with ng-bind-html-unsafe
...
here is working PLUNKER for both $sce and directive examples...
回答2:
I would keep the stuff you insert in its own template and use ng-include (http://docs.angularjs.org/api/ng/directive/ngInclude).
Having a angular template (template.html) with the contents:
<strong>This is <a href="#">Something</a></strong>
You can include it with
<p ng-include="template.html"></p>
This results in sth like
<p ng-include="template.html"><span class="ng-scope"><strong>This is <a href="#">Something</a></strong></span></p>
回答3:
Angular selectively sanitizes certain HTML tags with ng-bind-html
so if you want all the tags you should use ng-bind-html-unsafe instead
but watch out of XSS attacks !
BTW
It's far better to follow the @Ed Hinchliffe piece of advice
来源:https://stackoverflow.com/questions/22808062/ng-bind-html-doesnt-work-for-input-tags