AngularJS jQuery DOM ready

Every developer that uses AngularJS has probably run into the issue that DOM manipulations inside controllers are being executed before the DOM element is even created.
In this post we’ll explore several solutions for this known problem.

AngularJS logo

AngularJS logo


There are many times that we need to perform DOM manipulations when the controller/view is loaded. The problem in AngularJS (and Javascript in general) is that the controller, where we wrote the DOM manipulation code, is loaded before the view and therefore the element still does not exist.

AngularJS jQuery

There are several solutions to this issue. I’ll list them from the best to the worst in the AngularJS best practices way:

  1. 1. Listen to the $viewContentLoaded broadcast event.
    $scope.$on('$viewContentLoaded', function(event) {
    //Your code goes here.
    });
    
  2. 2. Use $timeout with zero seconds timeout so the view will be loaded, and then our code will be executed in the next digest cycle.
    $timeout(function() {
    //Your code goes here.
    });
    
  3. 3. Use the jQuery old fashioned way. (Works in most scenarios)
    jQuery(window).ready(function() {
    //Your code goes here.
    })
    

Leave a Reply

Your email address will not be published. Required fields are marked *