Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

AngularJS: How to run additional code after AngularJS has rendered a template?

I have an Angular template in the DOM. When my controller gets new data from a service, it updates the model in the $scope, and re-renders the template. All good so far.

The issue is that I need to also do some extra work after the template has been re-rendered and is in the DOM (in this case a jQuery plugin).

It seems like there should be an event to listen to, such as AfterRender, but I can't find any such thing. Maybe a directive would be a way to go, but it seemed to fire too early as well.

I still am having the same base issue; the code inside of the $watch event fires before the template has been compiled and inserted into the DOM, therefore, the jquery plugin is always evaluating an empty table.
by

1 Answer

vishaljlf39
I had the same problem and came up with this snippet. It uses $watch and $evalAsync to ensure your code runs after directives like ng-repeat have been resolved and templates like {{ value }} got rendered.
app.directive('name', function() {
return {
link: function($scope, element, attrs) {
// Trigger when number of children changes,
// including by directives like ng-repeat
var watch = $scope.$watch(function() {
return element.children().length;
}, function() {
// Wait for templates to render
$scope.$evalAsync(function() {
// Finally, directives are evaluated
// and templates are renderer here
var children = element.children();
console.log(children);
});
});
},
};
});


Hope this can help you with your problem.

Login / Signup to Answer the Question.