Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create separate AngularJS controller files?

I have all of my AngularJS controllers in one file, controllers.js. This file is structured as follows:

angular.module('myApp.controllers', [])   .controller('Ctrl1', ['$scope', '$http', function($scope, $http) {       }])   .controller('Ctrl2', ['$scope', '$http', function($scope, $http) }   }]) 

What I'd like to do is put Ctrl1 and Ctrl2 into separate files. I would then include both files in my index.html, but how should that be structured? I tried doing some thing like this and it throws an error in the web browser console saying it can't find my controllers. Any hints?

I searched StackOverflow and found this similar question - however, this syntax is using a different framework (CoffeeScript) on top of Angular, and so I haven't been able to follow.


AngularJS: How do I create controllers in multiple files

like image 322
Beebunny Avatar asked Nov 20 '13 04:11

Beebunny


People also ask

Can we have multiple controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application. This approach will make your code cleaner and easy to maintain and upgrade. Angular creates one $scope object for each controller.

Can you create controller in AngularJS?

AngularJS ControllersAngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.

Can we have multiple modules in AngularJS?

Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.


1 Answers

File one:

angular.module('myApp.controllers', []); 

File two:

angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){  }]); 

File three:

angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){  }]); 

Include in that order. I recommend 3 files so the module declaration is on its own.


As for folder structure there are many many many opinions on the subject, but these two are pretty good

https://github.com/angular/angular-seed

http://briantford.com/blog/huuuuuge-angular-apps.html

like image 129
Fresheyeball Avatar answered Sep 26 '22 06:09

Fresheyeball