简体   繁体   English

在AngularJS指令中查找子元素

[英]Find child element in AngularJS directive

I am working in a directive and I am having problems using the parameter element to find its childs by class name. 我在一个指令中工作,我在使用参数element按类名查找其子节点时遇到问题。

.directive("ngScrollList", function(){
    return {
        restrict: 'AE',
        link: function($scope, element, attrs, controller) {

            var scrollable = element.find('div.list-scrollable');

            ...
        }
      };
})

I can find it by the tag name but it fails to find it by class name as I can see in the console: 我可以通过标签名称找到它,但它无法通过类名找到它,正如我在控制台中看到的那样:

element.find('div')
[<div class=​"list-viewport">​…​</div>​,<div class=​"list-scrollable">​…​</div>​]
element.find('div.list-scrollable')
[]

Which would be the right way of doing such thing? 这样做的正确方法是什么? I know I can add jQuery, but I was wondering if wouldn't that be an overkill.... 我知道我可以添加jQuery,但我想知道这是不是一个矫枉过正....

jQlite (angular's "jQuery" port) doesn't support lookup by classes. jQlite(angular的“jQuery”端口)不支持按类查找。

One solution would be to include jQuery in your app. 一种解决方案是在您的应用中包含jQuery。

Another is using QuerySelector or QuerySelectorAll : 另一个是使用QuerySelectorQuerySelectorAll

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. 我们使用element数组中的第一项,即HTML元素。 element.eq(0) would yield the same. element.eq(0)会产生相同的结果。

FIDDLE 小提琴

In your link function, do this: 在您的链接功能中,执行以下操作:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $ . 此外,在链接函数中,不要使用$命名scope变量。 That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables. 这是一个特定于内置角度服务的角度约定,并不是您想要用于自己的变量的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM