Reputation: 510
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
Upvotes: 2
Views: 10829
Reputation: 60396
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);
}
};
});
Upvotes: 4
Reputation: 28750
Angular does not have as verbose a .find( as jquery. You can use the regular dom queryselector though:
var movable = element[0].querySelectorAll("#moveWrapper")
console.log(movable.length)
Upvotes: 0