How to call function on page load in AngularJS ?

Today now in this post, I am going to show you an example of how to call controller function when any page will load in AngularJS application. We know sometimes we need to run the function when a page load like for an example if we need to check the user is login or not in AngularJS. So It is possible by fire one Ajax request When the Page is Load.

There are the several way to us for we can do this. Here I will give you two example for an execute function on page load. So now in this example i will give you a very simple example, so we can simply understand and use it properly.

At First Example by using “$window.onload ” attribute and Second one example “data-ng-init” function.

So, Let’s check the both example and try it by own.

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

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

Read Also: How to implement Google new reCAPTCHA Code in PHP?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →