【问题标题】:How I can get a click event我如何获得点击事件
【发布时间】:2014-01-11 12:34:26
【问题描述】:

您好,我已经绑定了一些 HTML 元素。看看下面的代码

<DIV ng-bind-html-unsafe="myHTML"></DIV>

在控制器代码中是

$scope.myHTML="<DIV ng-click="myFunc()"></DIV>"
$scope.myFunc= function(){
alert("TEST");
}

这里我的 html 已正确加载。当我单击 div 时,我无法收到警报。

【问题讨论】:

    标签: angularjs ng-bind-html


    【解决方案1】:

    ng-bind-html-unsafe 不支持指令。我们必须以某种方式编译绑定的 html。

    尝试通过编写指令来编译它:

    app.directive("compile",function($compile,$timeout){
        return {
           priority:-1,
           link:function(scope, element, attrs) {
             $timeout(function(){
               $compile(element.contents())(scope);
             });
    
           }
        }
    });
    

    使用它:

    <div ng-bind-html-unsafe="myHTML" compile></div>
    

    DEMO

    另一种解决方案是编写我们自己的 ng-bind-html

    app.directive("myNgBindHtml",function($compile){
        return {
           link:function(scope, element, attrs) {
    
             scope.$watch(attrs.myNgBindHtml,function(value){
               element.html(value);
               $compile(element.contents())(scope);
             })
           }
        }
    });
    

    DEMO

    【讨论】:

    • 它给了我以下错误 Uncaught Error: selectors not implemented
    • angular js有什么解决方案吗?我试图以以下格式编译它 $scope.myHTML = $compile($scope.myHTML)($scope);它在 div 上给我输出如下 [[object HTMLDivElement]]
    • @Shardul Pendse:我想出了一个可行的解决方案,我们必须编写另一个指令来编译它。
    • 你好@KhanhTO 感谢您的解决方案。在我这边,我从数据库中获取数据,然后准备一个 HTML 字符串,然后绑定它。那么当我如何控制 element.contents();它是空白的。那么有没有像回电这样的解决方案?意思是内容绑定后可以调用指令。
    • @KhanhTO 当我将 console.log(element.contents()) 放在您给出的示例中时,它会打印一些对象已绑定。我们如何才能弄清楚?
    【解决方案2】:

    您的代码中有语法错误:

    $scope.myHTML="<DIV ng-click="myFunc()"></DIV>"
    

    您应该在myFunc() 周围使用单引号,如下所示:

    $scope.myHTML="<DIV ng-click='myFunc()'></DIV>"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      相关资源
      最近更新 更多