加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用angular js绑定html元素中的javascript和ng-click事件?

发布时间:2020-12-17 17:13:53 所属栏目:安全 来源:网络整理
导读:我想在我的html页面中绑定以下json响应. json如下: {"key":{"text":"pFor more information,please visit a href = "javascript:void(0);" ng-click = "customizeWindow('http://www.google.com');"Support/a ./p"}} HTML页面 div ng-bind-html="messag
我想在我的html页面中绑定以下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.

因此:

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.

继续阅读:Angular on SCE – trustAsHtml method

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读