简体   繁体   English

将Angularjs服务注入控制器

[英]Injecting Angularjs service into controller

I'm building fairly simple Angularjs app, which includes simple js-based game, home view and game over view. 我正在构建一个相当简单的Angularjs应用,其中包括基于js的简单游戏,主视图和游戏视图。 I posted most of the code here 我在这里张贴了大部分代码

http://jsfiddle.net/Seasamh/5bqq1bj8/ http://jsfiddle.net/Seasamh/5bqq1bj8/

Here is the code for html templates 这是html模板的代码

home.html home.html的

    <span>This is a main page</span>
    <a ng-click="setRoute('game')">Play game</a>

game.html game.html

<div id="timer"></div>
<div class="col-md-6 left">
    <div id="leftNumber"></div>
</div>
<div class="col-md-6 right">
        <div id="rightNumber"></div>
</div>

game-over.html 游戏over.html

<span>Game over!</span>

I have problems with getting the actual code of the game to render, although timer starts and works. 尽管计时器启动并可以正常工作,但是在渲染游戏的实际代码时遇到了问题。 Game code is stored in service, which I'm trying to inject in controller. 游戏代码存储在服务中,我正在尝试将其注入控制器中。 So far I failed. 到目前为止,我失败了。

I'm also using jQuery with noConflict() to manipulate the DOM. 我还使用带有noConflict()的jQuery来操作DOM。 Thanks in advance. 提前致谢。

You are not declaring the controller properly when using the array syntax: 使用数组语法时,您没有正确声明控制器:

This: 这个:

gameApp.controller('mainController', ['$scope', '$location', 'game', function($scope, game){

Should be: 应该:

gameApp.controller('mainController', ['$scope', '$location', 'game', function($scope, $location, game){

The array notation is so the above code will continue to work if the javascript is minified. 数组表示法是这样的,因此,如果将JavaScript缩小,则上面的代码将继续起作用。 You list all the things that you'd like to inject as strings in the array, and then need to specify them in the same order as arguments to the function. 您将所有要作为字符串插入到数组中的东西列出,然后需要以与函数参数相同的顺序指定它们。

EDIT 编辑

Actually, it looks like your fiddle has a few other issues. 实际上,您的小提琴似乎还有其他一些问题。 I usually use plnkr, and I'm not sure how/where you're loading angular. 我通常使用plnkr,但不确定如何加载角度。 After fixing the above, I got the an error about the "gameApp" module not being available. 修复上述问题后,出现有关“ gameApp”模块不可用的错误。

I fixed that by fiddling w/the fiddle a bit. 我通过摆弄小提琴来解决这个问题。 But then the next error was that the Angular module "ngRoute" was not available. 但是,下一个错误是Angular模块“ ngRoute”不可用。 This is where I stopped, b/c I'm not sure how you tell fiddler to load the ng-route javascript file. b / c,这是我停下来的地方,我不确定您如何告诉小提琴手加载ng-route javascript文件。

I've answered the question you asked, hopefully your app now works outside of the fiddle. 我已经回答了您提出的问题,希望您的应用现在可以在小提琴之外使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM