Finding element children in angular directive
Your directive is placed outside of ng-view
(it's a parent of ng-view
) and it's trying to find an element that is dynamically inserted by the ng-view
directive.
Your directive is initialised as soon as your angular module is initialised, and at that time ng-view
hasn't had a chance yet to load the partial (due to async nature of fetching the partials), hence there's no child elements available to your finder.
You need to instruct your directive to run its logic only after the ng-view
has finished loading and embedding the partial. That can be accomplished by observing the $viewContentLoaded
event which is fired every time ng-view
has finished loading the partial:
app.directive('myMouseScroll', function(){
return {
restrict: 'A',
link: function(scope, element, attrs){
function myFunction(){
scope.lock = false;
scope.current = 0;
var movable = element.find('#moveWrapper');
console.log(movable.length);
// ...
}
scope.$on('$viewContentLoaded', myFunction);
}
};
});
Comments
-
arthurmchr about 2 years
I'm quite new to angular and facing a problem.
I'm not able to get a child element contained in the element on which i put my directive. The fact is that this child element is inside an ng-view element that is populated via my router.My directive is the following one :
app.directive('myMouseScroll', function(){ return { restrict: 'A', link: function(scope, element, attrs){ scope.lock = false; scope.current = 0; var movable = element.find('#moveWrapper'); console.log(movable.length); // ... } } });
The log display 0 and when I display the content of 'movable', I can see that my children have not been rendered (i can see all the ng comments but not the result).
I saw some topics talking about using a $timeout but I can't get it work in my case...
Any ideas would be helpfull for me !
PS: I'm using jQuery with angular
-
arthurmchr over 10 yearsI read on the doc : link that jQlite support the find method on tag name, but in my case I'm using jQuery with angular, so I think I could use find() in this way. I have also test your answer without success :(
-
Mathew Berg over 10 yearsThen the element does not exist yet. Do a document.getElementById("");
-
arthurmchr over 10 yearsYes I think the problem is due to the fact that the ng-view has not been rendered at the time I call the directive (which is on an parent element of the ng-view). document.getElementById returns null value.
-
arthurmchr over 10 yearsThanks, exactly what I was searching for without success !
-
Mathew Berg over 10 yearsMy suggestion would be to wire up a directive on the moveWrapper element so it can notify other when it's ready.