如何创建单独的 AngularJS 控制器文件? [英] How to create separate AngularJS controller files?

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

问题描述

我的所有 AngularJS 控制器都在一个文件中,controllers.js.该文件的结构如下:

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

我想做的是将 Ctrl1 和 Ctrl2 放入单独的文件中.然后我会将这两个文件都包含在我的 index.html 中,但是应该如何构建呢?我尝试做这样的事情,但它在 Web 浏览器控制台中抛出一个错误,说它找不到我的控制器.有什么提示吗?

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?

我搜索了 StackOverflow 并发现了这个类似的问题 - 但是,此语法在 Angular 之上使用了不同的框架(CoffeeScript),因此我无法遵循.

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:如何在多个文件中创建控制器

推荐答案

文件一:

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

文件二:

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

}]);

文件三:

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

}]);

以该顺序包含.我推荐 3 个文件,因此模块声明是独立的.

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

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

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