我想在我的html页面中绑定以下json响应.
json如下:
json如下:
{ "key":{ "text":"<p>For more information,please visit <a href = \"javascript:void(0);\" ng-click = \"customizeWindow('http://www.google.com');\">Support</a> .</p>" } }
HTML页面
<div ng-bind-html="message"></div>
控制器代码
$http({ method: 'GET',url:'DAYS.json' }).success(function(responsedata) { $scope.message=responsedata.key.text; }).error(function(responsedata){});
在控制器内部的customizeWindow函数
$scope.customizeWindow = function(url) { window.open(url,"_blank","toolbar=yes,scrollbars=yes,resizable=yes,top=70,left=190,width=970,height=460"); }
ng-bind-html绑定了html标签,但它剥离了javascript和ng-click事件.
当我检查元素并且链接不起作用时,我只获得支持.
请建议我一个解决方案.
解决方法
这是因为角度自动使用$sce – >严格的上下文转义.它允许你使用ng-bind-html但它不允许你添加像JS这样的恶意代码.
你所追求的是明确地将该段视为HTML.
你所追求的是明确地将该段视为HTML.
因此:
angular.module('app',["ngSanitize"]) // You have to include ngSanitize or it wouldn't work. .controller('Ctrl',function ($scope,$sce){ $scope.htmlData = <p>For more information,please visit <a href = \"javascript:void(0);\" ng-click = \"customizeWindow('http://www.google.com');\">Support</a> .</p> //Took from your example. $scope.$watch("htmlData",function(newValue){ $scope.trustedData = $sce.trustAsHtml(newValuew); }); });
HTML用法:
<p ng-bind-html="trustedData"></p>
角度资源:
Strict Contextual Escaping (SCE) is a mode in which AngularJS requires
bindings in certain contexts to result in a value that is marked as
safe to use for that context. One example of such a context is binding
arbitrary html controlled by the user via ng-bind-html. We refer to
these contexts as privileged or SCE contexts.As of version 1.2,Angular ships with SCE enabled by default.