window.onload does not work in AngularJS

Curt picture Curt · Oct 25, 2012 · Viewed 48.7k times · Source

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?

Answer

Mo. picture Mo. · Dec 15, 2014

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>