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

How to run function in AngularJS controller on document ready?

I include a function inside my angular regulator, I'd like this function to be run on a report prepared however I saw that precise runs it as the dom is made.

 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?
by

3 Answers

aashaykumar
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';
});
}]);
sandhya6gczb
Execute angular contoller function on page load
// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
// check if there is query in url
// and fire search in case its value is not empty
};
pankajshivnani123
I had a similar situation where I needed to execute a controller function after the view was loaded and also after a particular 3rd-party component within the view was loaded, initialized, and had placed a reference to itself on $scope. What ended up working for me was to setup a watch on this scope property and firing my function only after it was initialized.

// $scope.myGrid property will be created by the grid itself
// The grid will have a loadedRows property once initialized

$scope.$watch('myGrid', function(newValue, oldValue) {
if (newValue && newValue.loadedRows && !oldValue) {
initializeAllTheGridThings();
}
});

The watcher is called a couple of times with undefined values. Then when the grid is created and has the expected property, the initialization function may be safely called. The first time the watcher is called with a non-undefined newValue, oldValue will still be undefined.

Login / Signup to Answer the Question.