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
406 views
in Technique[技术] by (71.8m points)

javascript - 如何创建单独的AngularJS控制器文件?(How to create separate AngularJS controller files?)

I have all of my AngularJS controllers in one file, controllers.js.

(我将所有AngularJS控制器都放在一个文件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.

(我想做的是将Ctrl1和Ctrl2放入单独的文件中。)

I would then include both files in my index.html, but how should that be structured?

(然后我会在index.html中包含这两个文件,但是应该如何构建呢?)

I tried doing some thing like this and it throws an error in the web browser console saying it can't find my controllers.

(我尝试做这样的事情,它在Web浏览器控制台中抛出一个错误,说它无法找到我的控制器。)

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.

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


AngularJS: How do I create controllers in multiple files

(AngularJS:如何在多个文件中创建控制器)

  ask by Beebunny translate from so

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

1 Reply

0 votes
by (71.8m points)

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.

(我推荐3个文件,因此模块声明是独立的。)


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

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

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

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


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

...