AngularJS - How to call function on page load example with demo?

By Hardik Savani | September 5, 2016 | | 5047 Viewer | Category : jQuery AngularJS


Share this post:

Today, I am going to show you how to call controller function when page will load in AngularJS. We sometimes require to run function when page load like for example if you need to check user is login or not in AngularJS, It is possible by fire one Ajax request When Page Load.

There are several way to you can do this. I have two example for execute function on page load. In this example i give you very simple example, so you can simply understand and use it properly.

First Example using "data-ng-init" attribute and Second example "$window.onload" function.

So, Let's check both example and try it...

Example 1:

<!DOCTYPE html>

<html>

<head>

<title>Angularjs call function on page load</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>

</head>

<body>


<div ng-app="myApp" ng-controller="mainController" data-ng-init="init()">

<h2>Angularjs call function on page load</h2>

</div>


<script type="text/javascript">

var myApp = angular.module("myApp", []);


myApp.controller("mainController", function($scope, $window) {


$scope.init = function () {

alert("Angularjs call function on page load");

};


});


</script>


</body>

</html>

Example 2:

<!DOCTYPE html>

<html>

<head>

<title>Angularjs call function on page load</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>

</head>

<body>


<div ng-app="myApp" ng-controller="mainController">

<h2>Angularjs call function on page load</h2>

</div>


<script type="text/javascript">

var myApp = angular.module("myApp", []);


myApp.controller("mainController", function($scope, $window) {


$window.onload = function() {

alert("Angularjs call function on page load");

};


});


</script>


</body>

</html>






We are Recommending you: