How to run function in AngularJS controller on document ready?

Shai UI picture Shai UI · Sep 6, 2013 · Viewed 408.4k times · Source

I have a function within my angular controller, I'd like this function to be run on document ready but I noticed that angular runs it as the dom is created.

 function myController($scope)
 {
     $scope.init = function()
     {
        // I'd like to run this on document ready
     }

     $scope.init(); // doesn't work, loads my init before the page has completely loaded
 }

Anyone know how I can go about this?

Answer

Will picture Will · Sep 6, 2013

We can use the angular.element(document).ready() method to attach callbacks for when the document is ready. We can simply attach the callback in the controller like so:

angular.module('MyApp', [])

.controller('MyCtrl', [function() {
    angular.element(document).ready(function () {
        document.getElementById('msg').innerHTML = 'Hello';
    });
}]);

http://jsfiddle.net/jgentes/stwyvq38/1/