1

I have a Service and a controller in my AngularJS App, that should be in the same module, but are two different files:

// File 1 (Service)
angular.module('myService', ['ngRoute'])
.service('myService', // ... 


// File 2 (Controller)
angular.module('myController', ['ngRoute'])
.controller('myController', // ..

This works fine. Now I want to have Service & Controller in one Module so I can load just one instead of two Modules. So I change the first line (of both files) to:

// Change in both files:
angular.module('myModule', ['ngRoute'])

But now I get an error:

Error: [$injector:unpr] ...

Maybe somebody knows, what could be wrong here. Thank you very much!

2 Answers 2

1

You can do the following:

var myApp = angular.module('myApp', []);

myApp.controller("myService"

myApp.service("myApp")

Or

angular.module("myModule").controller

angular.module("myModule").service

If you use angular.module('myService', []) twice, you are initializing the same module twice. If you just use angular.module("myModule"), without the dependencies, you are just calling it.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reply, Michael. Your first snippet: I have to use line 1 (very MyApp = ....) twice (in both files), right? Your second snippet: Where do I declare the Module "myModule"? Or can I just use it, without declaring it?
If a variable in the first script is visible in the second script, you can initialize the module in the first one. Just to see how it could be: -first approach: jsfiddle.net/yfvrjxve -second approach jsfiddle.net/yfvrjxve/3
Thank you very much Michael, it works perfect (I use the second approach). :)
1

You have two options -

  1. use a variable as mentioned by Michael

OR

  1. Use it like -

// Initialize myService Module in any JS file 
   (make sure this file is included before File 1 and File 2
angular.module('myService', ['ngRoute']);

// File 1 (Service)
angular.module('myService').service('myService', // ... 

// File 2 (Controller)
angular.module('myService').controller('myController', // ..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.