我从 Angular 开始,如何将一个应用程序的所有代码分解成多个文件?我看了 60 多分钟的介绍,他们提到我可以在没有 requirejs 或任何其他框架的情况下做到这一点。
假设我有这样的东西,效果很好:
var app = angular.module('app', []);
app.factory('ExampleFactory', function () {
var factory = {};
factory.something = function(){
/*some code*/
}
return factory;
});
app.controller ('ExampleCtrl', function($scope, ExampleFactory){
$scope.something = function(){
ExampleFactory.something();
};
});
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'ExampleCtrl',
templateUrl: 'views/ExampleView.html'
})
.otherwise({ redirectTo: '/' });
});
如果我想将它放在单独的文件中怎么办?像这样
文件一:
angular.module('factoryOne', [])
.factory('ExampleFactory', function () {
var factory = {};
factory.something = function(){
/*some code*/
}
return factory;
});
文件二:
angular.module('controllerOne', ['factoryOne'])
.controller ('ExampleCtrl', function($scope,ExampleFactory){
$scope.something = function(){
ExampleFactory.something();
};
});
文件三:
angular.module('routes', ['controllerOne'])
.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'ExampleCtrl',
templateUrl: 'views/ExampleView.html'
})
.otherwise({ redirectTo: '/' });
});
文件四:
var app = angular.module('app', ['routes']);
我试过了,还是不行。 我可以做这样的事情并在主视图中只为文件四添加一个脚本标签吗?还是每个文件必须有一个脚本标签? 感谢大家的帮助。
最佳答案
AngularJS 目前没有脚本加载器作为框架的一部分。为了加载依赖项,您需要使用第三方加载器,例如 RequireJS、script.js 等。
根据文档(http://docs.angularjs.org/guide/module#asynchronousloading):
Asynchronous Loading
Modules are a way of managing $injector configuration, and have nothing to do with loading of scripts into a VM. There are existing projects which deal with script loading, which may be used with Angular. Because modules do nothing at load time they can be loaded into the VM in any order and thus script loaders can take advantage of this property and parallelize the loading process.
...或者,正如@xanadont 解释的那样,您可以添加 <script>
为每个文件在您的页面上添加标签。
关于javascript - 你可以使用 Angular 依赖注入(inject)而不是 RequireJS 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409682/