问题
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 controllers are run. I want the game to be instantiated by a service so that I can expose it to other controllers, which do interact with the game in some capacity. I use $window.onload, but it only works when the page first loads. When I refresh the page, the event doesn't fire, presumably because the browser is getting the images from the cache.
I've considered using document.ready, but this will occasionally cause problems when the images haven't loaded quickly enough.
I've tried jQuery, vanilla JS, and Angular's syntax:
$(window).on('load', function() {});
$window.onload = function();
angular.element($window).on('load', function() {});
Any advice would be greatly appreciated. This is what my code basically looks like.
// Game Service (game state, game logic and game loop)
gameApp.service('theGame', function($log, $document, $window,
$location, $timeout, $interval) {
$window.onload = function() {
// Initialize a new Game object
var game = new Game();
game.initGame();
};
});
回答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 = new Game();
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)
1
来源:https://stackoverflow.com/questions/43877226/using-window-onload-in-angularjs-service