AngularJS:如何在多个文件中创建控制器 [英] AngularJS: How do I create controllers in multiple files

查看:21
本文介绍了AngularJS:如何在多个文件中创建控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我的控制器拆分成多个文件,但是当我尝试在我的模块中注册它们时,我收到一个错误:

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) -> 

错误

错误:参数GroupController"不是函数,未定义

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

从文档中我并没有真正了解模块方法的作用.它是否使用密钥Webchat"存储我的控制器?

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

似乎传递 [] 会创建一个新模块并覆盖前一个模块

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');

推荐答案

检查代码中引用GroupController"的其他位置(可能在您的路由中).有可能你把它当作一个变量,但是当你在模块中声明一个控制器时,你必须用引号将它包装起来.EG:

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})

工作正常,因为 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' 需要在路由中引用.

'GroupController' needs quotes in the route.

这篇关于AngularJS:如何在多个文件中创建控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆