【问题标题】:AngularJS : How to bind an event to a dynamically generated html with ng-bind-htmlAngularJS:如何使用 ng-bind-html 将事件绑定到动态生成的 html
【发布时间】:2014-10-19 12:56:39
【问题描述】:

我正在开发一个自定义 AngularJS 指令。如何将事件绑定到由指令本身生成的动态生成的 html。经过研究,我发现我们需要使用 $watch$compile,但我无法让它工作。我发现这个answer 与我的问题相关。 AngularJS 中 jQuery ON 的替代方法是什么

非常感谢任何帮助。请查看plunker

app.directive( 'btn', [ '$sce', function( $sce ){ 
return { 
    restrict: 'E',
    replace: true,
    template: '<div ng-bind-html="buttonHtml"></div>',
    link : function ($scope, element, attrs) {
    $scope.buttonHtml = $sce.trustAsHtml('<button ng-click="showMessage()">Click Me</button>');
    $scope.showMessage = function () {
        alert("You clicked Me");
  }
} }; }]);

提前致谢

【问题讨论】:

  • 您能否发布您已经使用 $watch 和 $compile 尝试过的代码,但您无法开始工作?
  • 您能不能展示一下您目前的成果,这样会更容易帮助您。
  • jqlite 不是为你做的吗?
  • @MichaelBromley 请稍候。我将使用代码示例编辑我的问题
  • @vishnu 如果您能够在plnkr.co 中发布您的代码,那将会很有用。

标签: javascript angularjs


【解决方案1】:

我希望这样:

app.directive('yourcustomdirective', function(){
  return {
    restrict : "E", //<---E is directive like <customdirective></customdirective>
    replace : true,
    template:"<button>Click me.</button>", // <---dynamically generated button
    link:function(scope, element, attrs){
      element.on('click', function(){ // <-----click event bound 
        alert(scope.greet); // <----alerts the greet in the scope
      });
    }
  };
});

Demo Plunkr.

Demo Plunkr with ng-click.

【讨论】:

  • 我有一个与此按钮关联的 ng-click。如何使 ng-click 起作用。
  • @vishnu 在控制器范围内创建一个函数并访问它。
  • 感谢您的帮助。我需要 doGreet() 函数也在指令中而不是在控制器中。
  • 问题出在使用 ng-bind-html 时。动态内容未触发该事件。请查看 plunker plnkr.co/edit/D5ll1mjzPVqbHHg2Tqb5
  • @vishnu 你有 angularjs 中可用的 jqlite 你可以使用这个element.find('button').on('click', callback);Read about jQlite here...!
猜你喜欢
  • 1970-01-01
  • 2014-01-14
  • 2014-03-31
  • 2018-04-06
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多