veeking
veeking

Reputation: 45

Angular directive can't get the child elements?

First, the directive selector-child is in the div element in the property.

 <div id="ed" selector-child>  // selector-child attrs directive
    <div class="testClass">Im no any directive</div>
    <div class="listClass" ng-repeat="aa in aas">Im has ng-repeate directive{{aa.text}}</div>      
 </div>

Then, the aas model data is also defined in the controller.

Finally, want to through the class name to search with ng-repeate directive of the elements in this list. The results showed that is empty,but no directive class name can be found, why? to solve???

myApp.directive('selectorChild', function () {
    return {
        restrict: "A",
        link: function (scope,element,attr) {
         console.log(element.find('.testClass'));
          // can be found -> ouput [div.testClass]
         console.log(element.find('.listClass'));
          // no found -> ouput is empty[]
        }
    };
});

Upvotes: 2

Views: 1320

Answers (2)

charlietfl
charlietfl

Reputation: 171669

try using $timeout to allow the ng-repeat to be generated in the dom

myApp.directive('selectorChild', function ($timeout) {
    return {
        restrict: "A",
        link: function (scope,element,attr) {
         $timeout(function(){
            console.log(element.find('.listClass'));
         });
        }
    };
});

As an alternative you could add another directive to the repeating elements that require this directive, then use $last property of ng-repeat child scope to do whatever it is you plan to do

Upvotes: 1

Avijit Gupta
Avijit Gupta

Reputation: 5756

You should use the querySelector method of JQlite:

 console.log(element[0].querySelector('.listClass'));

Upvotes: 2

Related Questions