AngularJS Wait for the last element to load before executing the directive
I am stuck with a problem in AngularJs and I cannot seem to solve it. (I'm new to Angular).
I have a container directive, a page directive and a content directive.
<container>
<page>
<contents></contents>
</page>
<page></page>
<page></page>
<!-- ... -->
</container>
On each page the link function adds 1 to the number of MasterService pages (a factory)
app.directive('page', function(Master) {
return {
restrict: 'E',
template: '<div ng-transclude></div>',
transclude: true,
scope: {},
link: function(scope, element, attrs) {
Master.pages ++;
}
}
});
This code works, however, when the content function is called (this function will be on the first or second page) to get the Master.page, I only get 1 or 2 because the following pages were not parsed. The only way I have found is to timeout $ when I want to get Master.pages
But I don't like it, how can I call the function after all pages have loaded?
thank
Since you are using a switch, the order of compilation, pre-link and post-link changes. (see Angular docs)
Instead of using a link, try using compilation like here: this way your counter will increment in the provisional link phase.
app.directive('page', function(Master) {
return {
restrict: 'E',
template: '<div ng-transclude></div>',
transclude: true,
scope: {},
compile: function(tElem, tAttrs){
return {
pre: function(scope, iElem, iAttrs){
Master.pages ++;
},
post: function(scope, iElem, iAttrs){
}
}
}
}
});
Just want to provide an alternative thought from @ user1802646.
How do you create pages? If they are data driven, can you use ng-repeat? You might be able to make a user "ng-repeat-end" to reach the timing you want.