简体   繁体   中英

Injecting Angularjs service into controller

I'm building fairly simple Angularjs app, which includes simple js-based game, home view and game over view. I posted most of the code here

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

Here is the code for html templates

home.html

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

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

<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. 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. 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. After fixing the above, I got the an error about the "gameApp" module not being available.

I fixed that by fiddling w/the fiddle a bit. But then the next error was that the Angular module "ngRoute" was not available. This is where I stopped, b/c I'm not sure how you tell fiddler to load the ng-route javascript file.

I've answered the question you asked, hopefully your app now works outside of the fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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