Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call AngularJS function on document ready

Is there a way to call an Angular function from a JavaScript function?

function AngularCtrl($scope) {   $scope.setUserName = function(student){       $scope.user_name = 'John';   } } 

I need the following functionality in my HTML:

jQuery(document).ready(function(){   AngularCtrl.setUserName(); } 

The problem here is my HTML code is present when page is loaded and hence the ng directives in the html are not compiled. So I would like to $compile(jQuery("PopupID")); when the DOM is loaded.

Is there a way to call a Angular function on document ready?

like image 968
Chubby Boy Avatar asked Dec 12 '12 10:12

Chubby Boy


People also ask

How do I run a function in AngularJS controller on document ready?

For running function in AngularJS controller on document ready you can use the angular. element(document). ready() method to attach callbacks for when the document is ready.

How can we call document ready function in AngularJS?

For fast lookup: // 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 }; This way, You don't have to wait till document is ready.

What is $viewContentLoaded?

$viewContentLoading only seems to get fired the first time content is loaded into the view. $viewContentLoaded gets fired every time, but doesn't have any info about the view.

Where does document ready function go?

The document ready function will wait until the DOM is loaded before running. So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded.


1 Answers

Angular has its own function to test on document ready. You could do a manual bootstrap and then set the username:

angular.element(document).ready(function () {     var $injector = angular.bootstrap(document, ['myApp']);     var $controller = $injector.get('$controller');     var AngularCtrl = $controller('AngularCtrl');     AngularCtrl.setUserName(); }); 

For this to work you need to remove the ng-app directive from the html.

like image 170
asgoth Avatar answered Oct 01 '22 09:10

asgoth