Angularjs call ajax function on page load

Call ajax function on page load: Here in this article will learn how to call controller function when our webpage gets loaded. While developing project many time we need to call some javascript functions directly after the page gets loaded. For example, we want to display some popup message on page load in AngularJS or show some notification message as soon as the HTML rendered.
Sometimes we also need to call some API or ajax call, so here we were going to see how to call ajax method whenever the page gets loaded i.e onload in angularjs application.

With these 2 ways, we can execute ajax function after page load.

Using ng-init() directive.

Call method on $window.onload.

Step to call ajax method onload in AngularJS.

Add ng-app directive and the Angularjs script.

Create and define controller with $http service.

CODE: Calling controller function which we want to get called when the page gets renders.

# Add ng-app directive and the Angularjs script

Before writing any code first, we want to download and import Angularjs script file on our webpage. We can download AngularJS files from angularjs.org, or we can include Google hosted files cdn. After importing Angularjs file, add Directive ng-app & ng-controller to the body tag.

# Create and define controller with $http service.

In our HTML body tag, we already added an attribute ng-controller with having value myController i.e. the name of our controller. Also as we want to make an ajax call, we need to add $http service . $http is an AngularJS service which is used to transfer data from remote server.

If you from jQuery background then you must familiar with the $.ajax() method, which is used to make ajax call, but in angularjs, we use $http service. Here we make an ajax call by calling GitHub API, which gives JSON response. Our final code looks like as written below.

Example 2: Using $window.onload

Another way to do it by using $window.onload, for that first we need to add $window in our controller. Then by putting an Ajax function on $window.onload, will execute the ajax request whenever the page gets loaded. The code looks like as written below.