Not only can you split your controller code between different files, but you probably should do it. The angular controller is responsible for the business logic for the presentation, and just for that. You do it wrong if you are inside the controller (the list is not exhaustive):
- access to your server from it
- DOM manipulation
- utility code for displaying warnings in the application (for example)
Your components must be concise and have a single responsibility .
The following is an example of how you export part of the code to a service. You do not link the js file to the controller, but upload it to your page and enter the service as an argument to your controller:
1) Download your service in index.html:
<script src="js/factories/loggerService.js"></script>
2) Deploy your service in loggerService.js
app.factories('loggerService', function () { // // Implement here some logging methods // // IMPORTANT: do not bloat this service with methods not related // with logging // });
3) Add your service to the controller:
app.controller('demoCtrl', function ($scope, loggerService) { loggerService.info(...) });
By the way, this loggerService would be useful only if you need something other than the service provided by angular's built-in $log service
source share