在AngularJS服务中使用window.onload [英] Using window.onload in AngularJS service

查看:236
本文介绍了在AngularJS服务中使用window.onload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AngularJS 1.6来创建依赖于某些图像的游戏.游戏在大多数情况下都与Angular分开,并在运行任何控制器之前由服务实例化.我希望游戏可以通过服务实例化,以便可以将其公开给其他控制器,这些控制器确实可以与游戏进行交互.我使用$ window.onload,但它仅在页面首次加载时有效.当我刷新页面时,该事件不会触发,可能是因为浏览器正在从缓存中获取图像.

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.

我已经考虑过使用document.ready,但这有时会在图像加载速度不够快时引起问题.

I've considered using document.ready, but this will occasionally cause problems when the images haven't loaded quickly enough.

我已经尝试过jQuery,香草JS和Angular的语法:

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();
    };

});

推荐答案

在AngularJS服务中放入window.onload会将购物车放在马头上. AngularJS在onload事件之后加载.

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

相反,请使用angular.element加载游戏,然后手动引导AngularJS:

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']);
});

为避免自动初始化,请记住忽略ng-app指令.

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.

加载或定义模块后,应调用angular.bootstrap().在应用程序引导后,您将无法添加控制器,服务,指令等.

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开发人员指南-引导程序(手动初始化)

注意: angular.element(f) 1

这篇关于在AngularJS服务中使用window.onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆