Sabarish Sankar Sabarish Sankar - 1 month ago 18
AngularJS Question

Call angular function on document ready

Is there a way to call angular function from 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? can anyone help me with this?

Answer

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.