Executing a function once the page is fully loaded in AngularJS
Asked Answered
N

3

6

I would like to execute this function as soon as the page is fully loaded.

vm.pointInvoice = () => {   
    if ($stateParams.property == "INVOICE") {
        vm.invoiceEdit($stateParams.checkin)
        vm.invoiceFocus = true;
        vm.receiptFocus = false;
    }
}

If I put the function as a button (just to test it), everything works perfectly

<button ng-click="vm.pointInvoice()">OPEN AND POINT TO INVOICE</button>

But, no matter what I do - I simply cannot get this to execute my function automatically (when the page is fully loaded and all data/elements are available).

Lucky me Stack Overflow had a lot of posts about page fully loaded so I tried a whole bunch of them but none of them works, they all fire off the function while the page is still blank.

These are some of the ones I have tried:

$scope.$on('$viewContentLoaded', function(){
    debugger;
});

angular.element(document).ready(function () {
    debugger;
});

$scope.$on('$stateChangeSuccess', function () {
    debugger;
});

So my only idea left is to do some ugly setTimeout(function(){ vm.pointInvoice() }, 3000); hack but to me thats a bit like giving up :-D

There MUST be some way to fire off an function when the page is fully loaded....

Nussbaum answered 30/8, 2017 at 11:49 Comment(0)
C
5

You may want to use the ng-init directive:

<div ng-init="init()">...</div>

Define this function is your controller:

$scope.init = function() {
    alert("Page is fully loaded!);
}

Anyway, you can call this function directly from your controller. It will be call once the app and the controller are loaded.

Cough answered 30/8, 2017 at 11:54 Comment(2)
Im gonna give it a tryNussbaum
I added it to the table where I needed the function to go and do stuff - and IT WORKED!!! Thank you so much @Mistralis!! <table class="book-table book-table-gray" ng-if="vm.invoiceRecord[0]._id" ng-cloak="" ng-init="vm.pointInvoice()">Nussbaum
S
0

Did you try using the right angular event?

Angular < 1.6.X

angular.element(document).ready(function () {
    alert('page loading finshed');
});

Angular >= 1.6.X

angular.element(function () {
    alert('page loading finshed');
});
Spinule answered 30/8, 2017 at 11:53 Comment(1)
Yes tried that already, but fires when the page is still blank (for some reason)Nussbaum
K
0

Have you tried something outside Angular JS?

$(document).ready(function(){ /*code*/ }); //with jQuery

document.addEventListener('DOMContentLoaded', function(){ /*code*/ });
Kooima answered 30/8, 2017 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.