jQuery ng-click 不适用于动态生成的 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19267979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:34:28  来源:igfitidea点击:

ng-click not working from dynamically generated HTML

jqueryhtmlangularjs

提问by Kiran Kumar

HTML

HTML

<table data-ng-table="tableParams" class="table table-bordered table-hover " style="border-collapse:collapse" data-ng-init="host.editSave = false" >
    <tr id="newTransaction">
    </tr>
    <tr data-ng-repeat="host in hosts|filter:search:strict" >
       <td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostCd}}</td>
       <td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostName}}</td>
    </tr>
</table>

Jquery

查询

$('#newTransaction').append(
 '<td contenteditable><input type="text" class="editBox" value=""/></td>'+ 
 '<td contenteditable><input type="text" class="editBox" value=""/></td>'+
 '<td>'+
    '<span>'+
        '<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>'+
    '</span>'+
 '</td>'
);

Angular Script

角度脚本

$scope.create = function() {
       alert("Hi");
    };

Here the function called in the controller part of the AngularJS is not getting trigger from the ng-click event. The Html is getting appended successfully, but the ng-click is not working. Tell me solutions to make it work

这里在 AngularJS 的控制器部分中调用的函数没有从 ng-click 事件中获得触发。Html 已成功附加,但 ng-click 不起作用。告诉我解决方案以使其发挥作用

回答by Arun P Johny

Not a perfect fix, still!!! - just to show how dynamic compilation can be done

不是一个完美的修复,仍然!!!- 只是为了展示如何进行动态编译

app.controller('AppController', function ($scope, $compile) {

    var $el = $('<td contenteditable><input type="text" class="editBox" value=""/></td>' +
        '<td contenteditable><input type="text" class="editBox" value=""/></td>' +
        '<td>' +
        '<span>' +
        '<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>' +
        '</span>' +
        '</td>').appendTo('#newTransaction');
    $compile($el)($scope);

    $scope.create = function(){
        console.log('clicked')
    }
})

Demo: Fiddle

演示:小提琴

Don't use controller for dom manipulation - it has to be done with the help of directives

不要使用控制器进行 dom 操作 - 它必须在指令的帮助下完成

回答by Maxim Shoustin

To make ng-clickto work we need to compilethis source by using $compileservice. Angular should know about new generated HTML and therefore this HTML should be included to digest cycle in order to trigger ng-clickand other events.

为了ng-click工作,我们需要使用服务来编译这个源代码$compile。Angular 应该知道新生成的 HTML,因此应该将此 HTML 包含到消化循环中以触发ng-click和其他事件。

See Fiddle

Fiddle

Create "compilator":

创建“编译器”:

.directive( 'compileData', function ( $compile ) {
  return {
    scope: true,
    link: function ( scope, element, attrs ) {

      var elmnt;

      attrs.$observe( 'template', function ( myTemplate ) {
        if ( angular.isDefined( myTemplate ) ) {
          // compile the provided template against the current scope
          elmnt = $compile( myTemplate )( scope );

            element.html(""); // dummy "clear"

          element.append( elmnt );
        }
      });
    }
  };
});

after, create dummy factorythat simulates your append:

之后,创建factory模拟您的追加的虚拟对象:

.factory( 'tempService', function () {
  return function () { 
    return '<td contenteditable><input type="text" class="editBox" value=""/></td>'+ 
            '<td contenteditable><input type="text" class="editBox" value=""/></td>'+
             '<td>'+
                '<span>'+
         '<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>'+
              '</span>'+
            '</td>';
  };
});

And finally call it like:

最后称之为:

<div compile-data template="{{mainPage}}"></div> 

in Controller:

在控制器中:

$scope.newTransaction= tempService();

For your example should be something like:

对于你的例子应该是这样的:

<table data-ng-table="tableParams" class="table table-bordered table-hover " style="border-collapse:collapse" data-ng-init="host.editSave = false" >
    <tr compile-data template="{{newTransaction}}">
    </tr>
    <tr data-ng-repeat="host in hosts|filter:search:strict" >
       <td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostCd}}</td>
       <td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostName}}</td>
    </tr>
</table>

BTW, for now you can use the same directive over your code and compile any dynamic HTML.

顺便说一句,现在您可以在代码上使用相同的指令并编译任何动态 HTML。

回答by porya ras

you can use angular.element(this).scope()without use of ng-click

您可以在angular.element(this).scope()不使用 ng-click 的情况下使用

and change

和改变

'<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>'

'<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>'

To

'<button id="createHost" class="btn btn-mini btn-success" onclick="angular.element(this).scope().create()"><b>Create</b></button>'is good

'<button id="createHost" class="btn btn-mini btn-success" onclick="angular.element(this).scope().create()"><b>Create</b></button>'很好

回答by ricka

I needed to have Cordova open the dynamic link in a new window, so my solution was to put the ng-click on the parent element and look at the event.target to see what was clicked on:

我需要让 Cordova 在新窗口中打开动态链接,所以我的解决方案是将 ng-click 放在父元素上并查看 event.target 以查看单击的内容:

<p ng-bind-html="foo.barhtml" ng-click="generalClick($event)"></p>

then

然后

.controller('FooCtrl', function ($scope) {
    var html = '<a href="http://www.google.com">google.com</a>';

    $scope.foo.barhtml = html.replace(/href/g, 'data-href');

    $scope.generalClick = function(event){
        // have Cordova open the link in a browser window
        window.open(event.target.attributes['data-href'].value, '_system');
    }
})

回答by AMRESH PANDEY

you need to add $compile service here, that will bind the angular directives like ng-click to your controller scope.Something like:

您需要在此处添加 $compile 服务,这会将 ng-click 等角度指令绑定到您的控制器范围。类似于:

var divTemplate = '..your div template';
var temp = $compile(divTemplate)($scope); 

Then append it to the HTML:

然后将其附加到 HTML:

angular.element(document.getElementById('foo')).append(temp);

You can also bind the event to the div as following:

您还可以将事件绑定到 div,如下所示:

var div = angular.element("divID");
div.bind('click', $scope.addPhoto());