Skip to content Skip to sidebar Skip to footer

Using Window.onload In Angularjs Service

I'm using AngularJS 1.6 to create a game that relies on some images. The game is separate from Angular for the most part, and instantiated by a service, before any of the controlle

Solution 1:

Putting window.onload inside an AngularJS service is putting the cart before the horse. AngularJS loads after the onload event.

Instead, use angular.element to load the game and then manually bootstrap AngularJS:

angular.element(function() {
    var game = newGame();
    game.initGame();
    angular.module("myApp").value("theGame", game);
    angular.bootstrap(document, ['myApp']);
});

To avoid automatic initialization, remember to omit the ng-app directive.

Manual Initialization

If you need to have more control over the initialization process, you can use a manual bootstrapping method instead.

You should call angular.bootstrap() after you've loaded or defined your modules. You cannot add controllers, services, directives, etc after an application bootstraps.

— AngularJS Developer Guide - Bootstrap (Manual Initialization)

Note: angular.element(f) is an alias for angular.element(document).ready(f)

Post a Comment for "Using Window.onload In Angularjs Service"