javascript 循环遍历 AngularJS 指令中元素的子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28737342/
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-10-28 09:28:30  来源:igfitidea点击:

Loop through the children of an element in a AngularJS directive

javascriptangularjs

提问by Mark Sandman

I have a problem - I've forgotten how to code! I have an angularJS directive that is on a parent wrapper tag (a DIV) and in my directive I wish to loop through the children (first Child DIVs). I have the following

我有一个问题 - 我忘记了如何编码!我有一个 angularJS 指令,它位于父包装器标签(DIV)上,在我的指令中,我希望遍历子级(第一个子 DIV)。我有以下

<div data-check-attributes>
  <div data-ng-repeat="user in Users" data-id="{{ user.ID }}" data-ng-click="doSomething(user.ID)" data-new="{{ user.newUser }}" class="">
    <div> {{ user.userName }} </div>
    <div> {{ user.userAge }} </div>
  </div>
</div>

Now in my directive I wish to loop through the first child divs (there could be many of these, but I am seeing 10 users in my loaded view) and perform certain checks and modifications in my directive, using the data attributes, the $location object and potentially many more... however I can't remember how to loop through the first child divs, I seem to get errors with everything I tried... so far I have this, which doesn't work! In the example below I just want to write the data-id of the first child nodes to the console

现在在我的指令中,我希望遍历第一个子 div(可能有很多,但我在加载的视图中看到 10 个用户)并在我的指令中执行某些检查和修改,使用数据属性 $location对象,可能还有更多……但是我不记得如何遍历第一个子 div,我尝试的所有内容似乎都出错了……到目前为止,我有这个,但不起作用!在下面的示例中,我只想将第一个子节点的 data-id 写入控制台

.directive('checkAttributes', function ($location) {
        return{
            restrict: 'A',
            link: function (scope, element) {

            // will use $location later

                console.log(angular.element(element)[0]);  // this outputs the HTML
                console.log(angular.element(element)[0].children().length); // this errors, TypeError: object is not a function

                for (var i = 0; i < angular.element(element)[0].children.length; i++) {
                    console.log(angular.element(element)[0].children[i].getAttribute('data-id'));
                }

            }
        };
    });

I'm confused... please help!

我很困惑……请帮忙!

采纳答案by dfsq

If you are trying to access childrenproperty of the HTMLElement then you should read it like property.

如果您尝试访问childrenHTMLElement 的属性,那么您应该像读取属性一样阅读它。

Another thing is that elementis already an instance of angular.elementso no need to wrap it again:

另一件事是它element已经是一个实例,angular.element所以不需要再次包装它:

console.log(element[0]);  // DOM element
console.log(element[0].children.length);

However there is a set of convenience methods angular.elementobject provides. Those methods replicate some of the jQuery's methods, including $.fn.childrenmethod. In this case alternatively you can do

但是,angular.element对象提供了一组便利方法。这些方法复制了一些 jQuery 的方法,包括$.fn.children方法。在这种情况下,您也可以这样做

console.log(element);  // angular.element instance
console.log(element.children().length);

And finally, there is one more caveat: ngRepeatwill render its elements afteryour custom directive, so you can't access childrencollection yet. Simplest fix is to wrap your code into $timeoutservice, which will execute your logic in the next digest cycle, guaranteed after ngRepeatis complete:

最后,还有一个警告:ngRepeat您的自定义指令之后呈现其元素,因此您还不能访问children集合。最简单的解决方法是将您的代码包装到$timeout服务中,这将在下一个摘要周期中执行您的逻辑,保证ngRepeat完成后:

app.directive('checkAttributes', function($location, $timeout) {
    return {
        restrict: 'A',
        link: function(scope, element) {

            // will use $location later
            $timeout(function() {
                for (var i = 0; i < element[0].children.length; i++) {
                    console.log(element[0].children[i].getAttribute('data-id'));
                }
            });

        }
    };
});

Demo:http://plnkr.co/edit/oEOSY2e2E0mmLDQOHbff?p=preview

演示:http : //plnkr.co/edit/oEOSY2e2E0mmLDQOHbff?p=preview