gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:00:43 27 4
gpt4 key购买 nike

我正在尝试在我的 html 页面中绑定(bind)以下 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>

Controller 代码

$http({
method: 'GET',
url:'DAYS.json'

}).success(function(responsedata) {
$scope.message=responsedata.key.text;
}).error(function(responsedata){});

Controller 内部的 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 绑定(bind)了 html 标签,但它剥离了 javascript 和 ng-click 事件。当我检查元素并且链接不起作用时,我只会得到支持。

请给我一个解决方案。

最佳答案

发生这种情况是因为 angular 自动使用 $sce -> Strict Contextual Escaping。它允许你使用 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>

Angular 资源:

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

关于javascript - 如何使用angular js在html元素中绑定(bind)javascript和ng-click事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26363736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com