Charanjeet Kaur Charanjeet Kaur - 4 months ago 46
jQuery Question

angular - ng-if - how to callback after ng-if template has been rendered

in Angular, I need to call a function after an element with certain class has been loaded.
Display of the element is controlled via ng-if='expr'. Value of $scope.expr is set after some ajax call has responded.

Now, if I try putting $watch on expr, or using $evalAsync. it is not working. probably the reason being that these events are run before the template part actually runs.

Here is a sample code : http://jsbin.com/kuyas/1/edit
Here I need a callback sort of thing on ng-if that gets executed after the template has rendered.

Answer

Problem was that there is no way to know if angular is done with the digest loop, ensuring that all elements have been rendered.

To solve this issue, there were two options

  1. Wrap your callback function in a directive. include that directive in ng-if. and make that expression true only when u want your callback to be executed.
  2. Call your callback function inside, setTimeOut(function(){ ... }, 0); as browsers by default keep all events in a queue, therefore, when digest loop is running, your callback function will enter the queue and get executed as soon digest loop is over.
Comments