← Back to blog
AngularJS
28 March 2015 · 7 min read

AngularJS - After Render Directive

Do you ever wanted to execute code after your Angular template is completely rendered?

This post is the answer of how you can accomplish that.

This a simple tip, but I believe that can be really useful.

Add the following directive to your application.

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

Now, add the after-render directive to an element in your template:

<div after-render="missionCompled"></div>

At this point, your application will run the missionCompled function (or other that you want) in your controller, after the div is rendered.

You can see the working demo on JSFiddle.

I hope that this helps you.

Developer Insights

What I'm building, learning, and discovering each week.

By signing up, you'll get my free weekly newsletter plus occasional updates about my courses. You can unsubscribe anytime.