Mawg
Mawg

Reputation: 40140

Angular: Structuring code into many small files

I am fairly new to AngularJS. Things were going well, but my controller.js was huge, so I thought to split it into smaller files.

Now, my index.html header has these lines

  <script src="js/services/date_picker_service.js"></script>
  <script src="js/controllers/common.js"></script>
  <script src="js/controllers/overview_map_controller.js"></script>
  <script src="js/controllers/overview_locations_controller,%20.js"></script>
  <script src="js/controllers/other_controllers.js"></script>

and loading my app gives

Error: [$injector:unpr] Unknown provider: dateServiceProvider <- dateService
http://errors.angularjs.org/1.2.9/$injector/unpr?p0=dateServiceProvider%20%3C-%20dateService
    at https://code.angularjs.org/1.2.9/angular.js:78:12
    at https://code.angularjs.org/1.2.9/angular.js:3546:19
    at Object.getService [as get] (https://code.angularjs.org/1.2.9/angular.js:3673:39)
    at https://code.angularjs.org/1.2.9/angular.js:3551:45
    at getService (https://code.angularjs.org/1.2.9/angular.js:3673:39)
    at invoke (https://code.angularjs.org/1.2.9/angular.js:3700:13)
    at Object.instantiate (https://code.angularjs.org/1.2.9/angular.js:3721:23)
    at https://code.angularjs.org/1.2.9/angular.js:6772:28
    at https://code.angularjs.org/1.2.9/angular.js:6185:34

I am guessing that the problem is that the script files in the <header> load asynchronously?

QUestion: how do I fix this, so that I don't need to go back to one humungeous controller.js?


[Update] I made a stupid error when splitting the big file into small ones & forgot the date service. So sorry. I awarded the answer to the oen who's post made me think D'oh! Sorry to waste your time.

Upvotes: 0

Views: 96

Answers (1)

Nikola Yovchev
Nikola Yovchev

Reputation: 10226

Probably you can refactor your controller, and have it have its data come from multiple services, so your controller would appear smaller.

Another thing you can do is split the controller into multiple controllers for subcomponents of your view.

A controller is basically responsible for a view. I can't imagine a controller requiring more than 4-5 things to be loaded at the same time. Refactoring is the way to go for you, I recon.

Apart from that, here is a way to define a controller that depends on a service:

angular.module('someModule', ['depends.on.otherModule'])

.controller('MyController',['Service', function(Service){

...codez
}]);

So in your case your controllers should be a part of a module that depends on the module which date_picker_service.js brings to the table.

Upvotes: 1

Related Questions