Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: callback after render (work with DOM after render)

Tags:

angularjs

How can run a method $scope.myWork() after render template? I want to set the $scope.value and after that I need to change something with JQuery (eg. in DOM of template content). $scope.$watch('value', function (){....}) is working "before" render (DOM of template is not available yet). Thanks.

like image 757
user1595465 Avatar asked Aug 14 '12 13:08

user1595465


People also ask

How does it work in angular?

It works by detecting side-effect event of AngularJS DOM rendering (you detect resize event of ul container) instead of direct information from AngularJS.

When does angular change the Dom?

Sign in to your account We often need to do some operations on DOM nodes, e.g. bind custom events to them (like "mouseover", "click" or "dblclick"), but Angular changes DOM eventually at the end of digest cycle.

Is it possible to bind a handler upon DOM modification by angular?

What we need is a way to bind some handler upon DOM modification by Angular is finished and it's safe to handle DOM elements (so they won't disappear next moment). From what I understand ng:init runs only once per node on first document rendering and doesn't guarantee any surrounding nodes are rendered.

What are the drawbacks of using AngularJS?

This solution also has it's drawbacks due to the way AngularJS operates. For example we put the image in the template that had a ng-repeat loop and we wanted to access the looped elements after they are in DOM.


2 Answers

Create a directive that runs your code in the link function. The link function is called after the template is built.

See ng-click to get an idea.

like image 63
Renan Tomal Fernandes Avatar answered Sep 19 '22 04:09

Renan Tomal Fernandes


I use terminal and transclude in a attribute directive to call a scoped method after a model is updated and view is rendered (in my case to resize a iframe after a $Resource.query):

.directive('postRender', [ '$timeout', function($timeout) { var def = {     restrict : 'A',      terminal : true,     transclude : true,     link : function(scope, element, attrs) {         $timeout(scope.resize, 0);  //Calling a scoped method     } }; return def; }]) 

The $timeout is black magic. It should be possible to declare the JS method as the attribute value and $parse it.

So I use it in a ng-repeat (in my case a tree is rendered recursively):

<div post-render ng-repeat="r in regions | orderBy:'name'" ng-include="'tree_region_renderer.html'"> 
like image 33
Jens X Augustsson Avatar answered Sep 18 '22 04:09

Jens X Augustsson