【问题标题】:angularjs click event inside the ngBindHtml directivengBindHtml 指令中的 angularjs 点击事件
【发布时间】:2016-03-29 04:33:01
【问题描述】:

我有一个 angularjs 示例代码 sn-p here,我可以在其中使用 ng-bind-html 指令绑定 html 标签。但是我怎样才能在 ngBindHtml 指令中包含一些其他标签,如 angularjs ng-clickid 标签等,如

<a href="javascript:void(0);" id="myLink" ng-click="myFunct()">Test</a>

我的示例代码在这里:

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "<a href='#' ng-click='someFunction()'>Test</a>";

    $scope.someFunction = function(){
    alert("Link Clicked");
    };
});

仅供参考,数据是从服务器端脚本动态加载的,我必须在ng-repeat 指令中使用ng-bind-html,并且我必须传递各自的ID 来单击事件,例如ng-click="myFunction(x.id)",如sample 2

【问题讨论】:

  • 这似乎会导致黑客能够在您的网站上运行不受信任的 javascript/html,这将是一件坏事。您可以通过 ng-include... 包含静态内容(或我想来自您的服务器的动态内容)...
  • mglison 是正确的,但是如果您控制正在显示的数据并且需要这样做,例如在数据表上的客户单元格中进行模板化(我之前使用过的用例) )。然后你需要 Angular 编译代码。我来看看 jsFiddle。

标签: angularjs ng-bind-html


【解决方案1】:

按照@Dr Jones 的建议,您需要使用$compile 指令。

jsfiddle 上的实时示例。

angular.module('ExampleApp', [])
  .controller('ExampleController', function($scope) {
    $scope.myText = "<button ng-click='someFunction(1)'>{{text}}</button>";
    $scope.text = "Test";
    $scope.someFunction = function(val) {
      console.log(val);
    };
  })
  .directive('bindHtmlCompile', function($compile) {
    return {
      restrict: "A",
      scope: {
        bindHtmlCompile: "="
      },
      link: function(scope, elem) {
        scope.$watch("bindHtmlCompile", function(newVal) {
          elem.html('');
          var newElem = angular.element(newVal);
          var compileNewElem = $compile(newElem)(scope.$parent);
          elem.append(compileNewElem);
        });
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">
    <h3>
  Write code for test button
  </h3>
    <textarea cols="100" ng-model="myText"></textarea>
    <div bind-html-compile="myText">

    </div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多