Search code examples
javascriptangularjsfunction-callangularjs-1.6

Executing a function once the page is fully loaded in AngularJS


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....


Solution

  • 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.