Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onload does not work in AngularJS

This code in a simple HTML file works:

<script>
  function load() {
    alert("load event detected!");
  }
  window.onload = load;
</script>

However, if I put it into the index.html file of an AngularJS web app, it does not. Does anybody know why not?

like image 779
Curt Avatar asked Oct 24 '12 23:10

Curt


People also ask

When window onload is fired?

The onload attribute fires when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

Is there an onload function in JavaScript?

In JavaScript, this event can apply to launch a particular function when the page is fully displayed. It can also be used to verify the type and version of the visitor's browser. We can check what cookies a page uses by using the onload attribute.

What is onload in angular?

onload in Angularjs :: onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include).

What is ngInit?

The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.


2 Answers

Call your function with ng-init

var app = angular.module('app',[]);
app.controller('myController', function($scope){
    $scope.load = function () {
        alert("load event detected!");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app'>
  <div ng-controller='myController' ng-init='load()'></div>
</div>
like image 78
Mo. Avatar answered Sep 23 '22 05:09

Mo.


I prefer putting this kind of code in the app.run() function of angular.

e.g.

angular
.module('testApp', ['someModule'])
.constant('aConstant', 'hi')
.config(function($rootProvider) {/*some routing here*/})
.run(['$window', function($window) {
  $window.onload = function() {/*do your thing*/};
}]);

also check this nice post that depicts the order that some things happen in angular AngularJS app.run() documentation?

like image 22
agelbess Avatar answered Sep 19 '22 05:09

agelbess