How to Call Function on Page Load in AngularJS?
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>
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- AngularJS Check Checkbox is Checked or Not Example
- AngularJS Convert Comma Separated String to Array Example
- AngularJS - How to Create Read More/Less Toggle using Directive?
- How to Call AngularJS Controller Function in JQuery?
- How to Remove # from URL in AngularJS?
- How to Hide Div After Some Time in AngularJS?
- AngularJS Pagination using dirPagination Directive Example
- AngularJS Sorting(using Orderby Filter) Table Data Example
- How to Change Date Format using Date Filter in AngularJS?
- AngularJS - How to Limit String Length using Filter?
- AngularJS - How to Capitalize the First Letter of Word Example
- How to Remove HTML Tags from String in AngularJS?
- PHP AngularJS CRUD with Search and Pagination Tutorial