Inside one of my custom directives, I have an ng-repeat
in the template.
myApp.directive("test", function () {
return {
restrict: 'C',
scope: {
bindVar: '='
},
template: '<div>\
<div class="item" ng-repeat="sel in bindVar">{{sel.display}}</div>\
</div>',
link: function ($scope, element, attrs) {
// setTimeout(function() {
alert($('.item').length); // <--- RETURNS 0, IF I ADD TIMEOUT RETURNS 3
// },0);
} // of link
} // of return
});
Check out this JSFiddle for reference
Despite calling the link()
function, I'm unable to access the newly created items directly. A workaround involves setting a timeout of 0 milliseconds (after that it works).
I came across a blog post discussing this issue in detail: Handling DOM Updates in AngularJS
Additionally, there's a related Stack Overflow thread where using Timeout was marked as the solution: DOM elements not ready in AngularJS Directive's link() function
Hopefully, there's a more elegant approach than relying on timeouts. Is there a built-in method in Angular to trigger a callback when the DOM is fully generated by a directive? Or are timeouts the only way to go? (really? :/)