Loop through child elements of an element in AngularJS directive

I have a problem - I forgot how to encode! I have an angularJS directive that is on the parent wrapper (DIV) tag, and in my directive I want to scroll the children (the first children of the DIV). I have the following

<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 want to skip the first child divs (there may be many, but I see 10 users in the loaded view) and perform certain checks and modifications in my directive using data attributes, the $ location object, and possibly many more .. However, I can’t remember how to iterate over the first child divs, I seem to get errors with everything I tried ... as long as I have it, that doesn't work! In the example below, I just want to write the data id of the first child nodes to the console

 .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 ... help!

+8
javascript angularjs
source share
1 answer

If you are trying to access the children property of the HTMLElement, you should read it as a property.

Another thing is that element already an instance of angular.element , so there is no need to wrap it again:

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

However, there are a number of convenient angular.element methods. These methods replicate some of the jQuery methods, including the $.fn.children method. In this case, you can also do

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

And finally, there is another caveat: ngRepeat will display its elements after your custom directive, so you still cannot access the children collection. The simplest fix is ​​to wrap your code in the $timeout service, which will execute your logic in the following digest loop guaranteed after ngRepeat completes:

 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

+4
source share

All Articles