Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

coffeescript - 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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...