如何从指令的链接函数的“element”参数中选择具有特定ID的元素,使用jQuery而不是angular的jqLite

How to select an element with a specific id from a directive's linking function's 'element' parameter, using jQuery rather than angular's jqLite?

本文关键字:元素 ID 使用 angular jqLite jQuery 链接 函数 指令 element 选择      更新时间:2023-09-26

这是指令的模板:
(如果我理解正确,这就是链接函数的"element"参数中可用的内容,不是吗?

template: '<div class="panel">' +
  '<div id="lh" title=""></div>' +
  '<div id="rh" title=""></div>' +
'</div>',

我读过jQuery优先于jqLight,当它在angular之前加载时。考虑到这一点,这是我尝试从链接函数中选择标有"lr"id 的div 并设置其"title"属性:

link: function(scope, element, attrs) {
  element.$('#link').attr("title", attrs.title);
}

这是行不通的,就好像没有jQuery一样。
如何以"Angular"方式做到这一点,同时利用jQuery?
谢谢你的时间。
杰瑞德

在jQuery中,你可以选择设置根目录,从它开始查找。

$(selector[, root])

在您的情况下,这将是

$("#lr", element)
另外值得注意的是,

在任何给定时间,页面上应该只有一个具有特定ID的元素,因此$("#lr")也应该有效。

基本上你需要获取模板的 HTML,然后使用 jqLite(或 jQuery)对象进行转换。

link: function (scope, element, attrs) {
    var html = element[0].innerHTML;
    var e = angular.element(html).find("#lr").attr('title', 'ABC');
    element.replaceWith(e);
}