我正在使用 AngularJS 1.6 创建一个依赖于某些图像的游戏。该游戏在很大程度上与 Angular 是分开的,并在任何 Controller 运行之前由服务实例化。我希望游戏由服务实例化,以便我可以将其公开给其他 Controller ,这些 Controller 以某种方式与游戏进行交互。我使用 $window.onload,但它仅在页面首次加载时起作用。当我刷新页面时,该事件不会触发,可能是因为浏览器正在从缓存中获取图像。
我考虑过使用 document.ready,但是当图像加载速度不够快时,这有时会导致问题。
我尝试过 jQuery、vanilla JS 和 Angular 的语法:
$(window).on('load', function() {});
$window.onload = function();
angular.element($window).on('load', function() {});
如有任何建议,我们将不胜感激。这就是我的代码的基本样子。
// 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();
};
});
最佳答案
将 window.onload
放入 AngularJS 服务中就本末倒置了。 AngularJS 在 onload
事件之后加载。
相反,使用angular.element
加载游戏,然后手动引导AngularJS:
angular.element(function() {
var game = new Game();
game.initGame();
angular.module("myApp").value("theGame", game);
angular.bootstrap(document, ['myApp']);
});
为避免自动初始化,请记住省略 ng-app
指令。
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)
注:angular.element(f)
是 angular.element(document).ready(f) 的别名 1
关于javascript - 在 AngularJS 服务中使用 window.onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43877226/