我是 AngularJS 的新手,并且有疑问如何从结构化文件夹中加载控制器和其他 js?
例如我有结构:
app/
-common
-users
--userController.js
--userService.js
-orders
-app.js
我应该如何从文件夹用户加载控制器和服务?
还有一个小问题:squre bracerts 是什么意思?
app.config(['someThing'], function($routeProvider)
我是 AngularJS 的新手,并且有疑问如何从结构化文件夹中加载控制器和其他 js?
例如我有结构:
app/
-common
-users
--userController.js
--userService.js
-orders
-app.js
我应该如何从文件夹用户加载控制器和服务?
还有一个小问题:squre bracerts 是什么意思?
app.config(['someThing'], function($routeProvider)
You can put the your code where you wants to. If you put them into angular modules, angular will find it. So if you have a service in /app/common/services/foo.js
like:
angular.module('app').service('foo', function() { ... });
You can do this in the userController
:
angular.module('app').controller('UserController', function($scope, foo) { ... });
Here you see how I injected foo
in our controller. Angular Dependency Injection
system is smart enough to find your code no matter where you put them.
You can also create different modules than app
, you can have:
angular.module('other').service('bar', function() { ... });
And where you define the app
module, something like this:
angular.module('app', []);
You just need to add the new module there as a dependency, that is what the []
are for:
angular.module('app', ['other']);
Now you can use the service bar
in your controller too :)
On the other hand, the syntax you're talking about is the array notation, something like this:
angular.module('app').controller('FooCtrl', ['$scope', 'foo', function($scope, foo) { ... }]);
This is needed if you mangle your code when you minify it because in the minified code, you could get something like this:
angular.module('app').controller('FooCtrl', ['$scope', 'foo', function(f, g) { ... }]);
As you see, the function parameters are now f
and g
and Angular doesn't know what to inject based on those names, so it looks on the strings we provided, so it will know that f
is $scope
and g
is foo
.
There is no need to use this annotation directly, there are several tools that will do that for you like ngmin.
Cheers.
EDIT: You would need to add every javascript file into a <script>
or the won't get loaded and Angular wouldn't find it.
Adding the files one by one is a pain, because you can have 5 or you can have 200.
It is better to concat them and for that I recommend: grunt-concat-sourcemap
because it will generate a sourcemap so you will have 1 file with the entire app but in the dev tools you will see them in separate files.
I recommend you to check linemanjs which is a good tool to develop javascript apps and it concat the files for you, source maps, minify, the array notation stuff also...
您必须链接主 HTML 页面中的所有文件并确保它们已加载。正如上面德怀特所指出的。
另一种方法是使用 Grunt.js 之类的东西来“构建”应用程序。这将包括将所有 controller.js 文件合并为一个 - 然后将其加载到 HTML 页面中。这样,所有文件都将单独用于开发,但将被编造用于部署。