15

I want to wrap this https://gist.github.com/nblumoe/3052052 in a module. I just changed the code from TokenHandler to UserHandler, because on every api request I want to send the user ID.

However I get module UserHandler not found in firebug console. Here is my full code: http://dpaste.com/1076408/

The relevent part:

angular.module('UserHandler').factory('UserHandler', function() {
    var userHandler = {};
    var user = 0;

    /...

    return userHandler;
});

angular.module('TicketService', ['ngResource', 'UserHandler'])
       .factory('Ticket', ['$resource', 'UserHandler',
                function($resource, userHandler){

    var Ticket = $resource('/api/tickets/:id1/:action/:id2',
    {
        id1:'@id'
    }, 

    { 
        list: {
            method: 'GET'
        }
    }); 

    Ticket = userHandler.wrapActions( Ticket, ["open", "close"] );

    return Ticket;
}]); 

Any idea why this happens? How to fix it?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

3 Answers3

40

Many has fallen into the same trap. Me included.

The following does not define a new module. It will try to retrieve a module named UserHandler which isn't defined yet.

angular.module('UserHandler')

Providing a (empty) array of dependencies as the second argument will define your module.

angular.module('UserHandler', [])
Bart
  • 17,070
  • 5
  • 61
  • 80
  • it's great that yo angular:controller creates something that doesn't work then! – mstreffo May 17 '14 at 11:50
  • 1
    I use yo to generate angular templates (see https://github.com/yeoman/generator-angular) and this creates a controller like this: angular.module('clientApp') .controller('MycontrollerCtrl', function ($scope) {...}) which does not work. I need to add [] to angular.module() for it to work. – mstreffo May 17 '14 at 19:38
  • 2
    This question is about defining modules. Your sample registers a controller with a existing module. You're suffering the same confusion :) – Bart May 18 '14 at 06:54
  • Not specific to this particular case but may help some (this post appears pretty high on google for this issue search): if your module is in a separate file, it also has to be included in the html: – timhc22 Sep 30 '14 at 23:35
2

I am new to javascript and have spent a couple of hours to discover my issue. The module initialization function can be ignored. To avoid this, do not forget to add empty parenthesis to the end of a function:

(function() {
    "use strict";
    var app = angular.module("app", []);
    })(); //<<---Here
Atchitutchuk
  • 174
  • 5
0

Also, don't forget to add the new module in your index.html:

<script src="app/auxiliary/test.module.js"></script>
<script src="app/auxiliary/test.route.js"></script>
<script src="app/auxiliary/test.controller.js"></script>
romin21
  • 1,532
  • 1
  • 14
  • 35