Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 285
Charanjeet Kaur Avatar asked Jun 26 '14 18:06

Charanjeet Kaur


2 Answers

One possible answer would be to create a directive that does whatever you want to do. If you then use that directive only within the section of HTML controlled by the ng-if, then the directive will be dormant until the ng-if expression is true.

Would that do what you want?

like image 128
John Munsch Avatar answered Oct 04 '22 05:10

John Munsch


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.
like image 41
Charanjeet Kaur Avatar answered Oct 04 '22 04:10

Charanjeet Kaur