AngularJS: How do I create controllers in multiple files

I'm trying to split my controllers into multiple files, but when i try to register them at my module im getting an error:

groupcontroller.coffee

app = angular.module('WebChat', []);
app.controller 'GroupController', ($scope) -> 

usercontroller.coffee

app = angular.module('WebChat', []);
app.controller 'UserController', ($scope) -> 

Error

Error: Argument 'GroupController' is not a function, got undefined

From the documentation I dont really get what the module method does anyway. Does it store my controller with the key 'Webchat'?

Edit: It also seems that passing [] creates a new module and overwrites the previous one

app = angular.module('WebChat', []);

To prevent this, you have to leave out the [] like

app = angular.module('WebChat');

Check other places in your code where you're referencing 'GroupController' (probably in your route). Chances are you have it as there as a variable, but when you declare a controller inside a module you'll have to wrap it quotes. EG:

MyCtrl1() = -> ()
...
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: MyCtrl1})

works fine because MyCtrl1 is a variable. But when declaring controllers in a module as you are:

app = angular.module('WebChat', []);
app.controller 'GroupController', ($scope) ->
   # ...

$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'GroupController'})

'GroupController' needs quotes in the route.


here is what I did:

index.html

<script src="js/angular.js" type="text/javascript" charset="utf-8"></script>
<script src="js/myApp.js" type="text/javascript" charset="utf-8"></script>
<script src="js/myCtrlA.js" type="text/javascript" charset="utf-8"></script>
<script src="js/myCtrlB.js" type="text/javascript" charset="utf-8"></script>

app.js

myApp = angular.module('myApp', [])
myApp.config ($routeProvider) ->
    $routeProvider.when('/a', {controller: 'myCtrlA', templateUrl: 'a.html'})
    $routeProvider.when('/b', {controller: 'myCtrlB', templateUrl: 'b.html'})

myCtrlA.js

angular.module('myApp').controller 'myCtrlA', ($scope) ->
    console.log 'this is myCtrlA'

myCtrlB.js

angular.module('myApp').controller 'myCtrlB', ($scope) ->
    console.log 'this is myCtrlB'

as you can see, if I have a lot of controller js files, that will be a lot of script elements in index.html too.
I don't know how to deal with that yet.

FYI: http://briantford.com/blog/huuuuuge-angular-apps.html
but this article did not mention the html file too.


I have my app var definied in my app.js file witch is first referenced and after that the controller files for example FirstCtrl.js.

so in app.js ex

var app = angular.module(...

in FirstCtrl.js

app.controller('FirstCtrl',
链接地址: http://www.djcxy.com/p/77930.html

上一篇: 将变量传递给AngularJS控制器,最佳实践?

下一篇: AngularJS:我如何在多个文件中创建控制器