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

How to bind javascript and ng-click event in html element using angular js?

本文关键字:javascript 绑定 ng-click 事件 元素 angular 何使用 js html      更新时间:2023-09-26

我正试图在我的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){});

自定义控制器内部的窗口功能

$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事件。当我检查元素并且链接不起作用时,我只得到支持。

请给我一个解决方案。

由于angular Automatically使用$sce->Strict Contextual Escapeng,因此会发生这种情况。它允许你ng绑定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资源:

严格上下文转义(SCE)是AngularJS需要在某些上下文中绑定,以生成标记为用于该上下文是安全的。这种上下文的一个例子是绑定用户通过ng-bind-html控制的任意html。我们参考这些上下文为特权上下文或SCE上下文。

从1.2版本开始,Angular默认情况下会启用SCE。

阅读:Angular on SCE-trustAsHtml方法

ng-bind-html内容在默认情况下是经过净化的,它并不意味着将DOM带入页面。您可以使用此方法将内容放到页面上。例如,如果你有一个富文本编辑器,你想给它提供html内容,无论多么干净,这就是你使用ng-bind-html的时候。

出于您的目的,我建议使用模板或纯模型绑定。

json的来源,不管怎样,都不应该真正了解消费者端(页面)的实现/技术——如果你离开angularJS并开始使用Knockout,你也必须更改服务器端,因为Knockout对点击一无所知。只要像这样把内容传回来http://www.google.com,'欲了解更多信息,请访问'并绑定。

 {
        "key":{
        "textsource": { 
                              source :  'http://www.google.com',
                              message : 'For more information, please visit  ' 
                       }
        }
     }
    <p>{{textsource.message}}<div  ng-click="customizeWindow(textsource.source)'">Support</div> </p>

如果你不能改变服务器端,看看这个例子:

1) 告诉$sce你的内容很好

 $scope.message = $sce.trustAsHtml(json.key.text);

2) 重新编译动态添加的内容

  $scope.init = function () {
            var el = document.getElementById("dynamic");
             $compile(el.childNodes[0])($scope);
        };

注意:重新编译步骤目前是手动的(按下重新编译按钮)。按照这个操作可以很好地工作。