【问题标题】:elem.find() is not working in AngularJS linkelem.find() 在 AngularJS 链接中不起作用
【发布时间】:2016-02-27 05:08:22
【问题描述】:

我有一个来自 templateUrl 的 Angular 'E' 指令,它描述了一个带有 ng-repeat 生成的行的表。在我的 link 名称中,我正在尝试将事件侦听器添加到该表中的按钮。

指令:

    .directive("reqParts", ["$http", function($http){
   return {
       restrict: 'E',
       templateUrl: '/public/reqParts.html',
       link: function(scope, elem, attr){
           elem.find('.approve').click(function(){
               console.log("clicked");
           });
       }
   };

模板网址:

<table class="table table-striped">
<tr>
    <th>User</th>
    <th>Title</th>
    <th>Waiting List</th>
</tr>
<tr ng-repeat="req in requests">
    <td>{{req.requestedBy[0].uname}}</td>
    <td>{{req.title}}</td>
    <td>{{req.requestedBy.length - 1}}</td>
    <td><button class='approve'>Approve</button></td>
</tr></table>

根据类似的问题,我的加载顺序是 Jquery -> Bootstrap -> Angular -> AngularDirective,所以这不应该是问题。

编辑: 我尝试过的一些事情:

$('.approve').click() 不起作用。

console.log($('.approve')) 返回 []。

console.log(elem.children().children()) 返回[tbody]

console.log(elem.find('button')) 返回 []。

elem.find('tr').click() 适用于表格的第一行,而不是第二行(不应该找到与选择器匹配的所有元素的集合吗?)

在控制台中,$('.approve') 有效,`$('table').find('.approve') 有效。

【问题讨论】:

  • jqlite, find 仅限于标签查找
  • 我刚刚尝试了一个 JQLite 建议 - angular.element(document.getElementsByClassName('.approve')) - 这也不起作用,所以它可能不是 JQLite/Jquery 问题,只是我的问题做错了。
  • 我在 Angular 之前加载 JQuery,所以它应该用 JQuery 覆盖 JQLite。
  • 你试过.on吗?查看this example
  • @kondrak 谢谢,但这意味着什么,来自 Angular 元素文档:If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or jqLite.

标签: jquery angularjs angularjs-directive jqlite


【解决方案1】:

谢谢你们的建议!事实证明,问题不在于 JQuery,而在于 ng-repeat。我遵循了此处描述的解决方法:AngularJS: Linking to elements in a directive that uses ng-repeat

创建一个指令属性,在 ng-repeat 工作完成时发出一个事件,传递的第二个参数是 JQuery 包装的行,它与 .find() 完美配合

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2014-04-12
    相关资源
    最近更新 更多