1

I am wondering if there is a way for Angular JS to identify the view has loaded completely. I need to call a function on route change . I tried it with $routeChangeSuccess. But the function is called before the view loaded completely. Is there any way to do this?

For example I am having a navigation menu, and I need to activate menu item while the root has changed. I am having a css class active for showing a menu item is active. I wrote a function to make it active. if the url is www.myweb.com/#/dashboard, then dashboard menu should be active. The function is working perfectly. But the problem is the function calls before the view loaded completely. So it won't activate the menu item because, menu item is not there.

If you have a solution, let us all know about that.

Sajith
  • 2,842
  • 9
  • 37
  • 49
  • For the case you have mentioned you don't require to know when view was loaded completely. Show how are you trying to set menu action and from where. – Chandermani Nov 29 '13 at 12:20

1 Answers1

0

I do not really know whether is a nice solution for it.

What works usually is waiting for one $digest loop to run which will render the HTML and then executing the DOM manipulating call. This can be done by wrapping the call to set the active class inside a $timeout call with a 0 delay, which will cause it to execute on the next tick.

Note that if you use setInterval for it, then you'll need a scope.$apply to tell Angular to rerun the $digest loop.

Example

app.directive('myDir', function ($timeout) {
    return {
       template: '<div>Message</div>',
       link: function (scope, elem) {
           $timeout(function () { elem.find('div').addClass('active'); });
       }
    };
});
musically_ut
  • 34,028
  • 8
  • 94
  • 106