Javascript 角度js分离到不同js文件中的不同模块

Javascript 角度js分离到不同js文件中的不同模块,javascript,angularjs,module,angularjs-directive,Javascript,Angularjs,Module,Angularjs Directive,我创建了一个angular web应用程序,它支持拖放元素 我完成了它,但我有一个大模块。该模块放在一个js文件中,包含数千行代码 我想知道如何将我的大模块划分为几个相互通信的js文件中的几个模块 有人能给我举个简单的例子吗 我想知道如何将我的大模块划分为几个相互通信的js文件中的几个模块 确保您可以使用多个模块并像下面的示例中那样绑定它们: var firstModule = angular.module('firstModule', []); var secondModule = angul

我创建了一个angular web应用程序,它支持拖放元素

我完成了它,但我有一个大模块。该模块放在一个js文件中,包含数千行代码

我想知道如何将我的大模块划分为几个相互通信的js文件中的几个模块

有人能给我举个简单的例子吗

我想知道如何将我的大模块划分为几个相互通信的js文件中的几个模块

确保您可以使用多个模块并像下面的示例中那样绑定它们:

var firstModule = angular.module('firstModule', []);
var secondModule = angular.module('secondModule', ['firstModule']);
现在,在
firstModule
中创建的所有服务/指令都可以在
secondModule
中看到

但在创建两个模块之前,您应该问问自己:

1。两个模块

var app = angular.module('myApp', []);

app.controller('someCtrl', function($scope) {

     // call other js file:
     otherFile($scope);

    /*....*/
});
app.$inject = ['$scope'];
var otherFile = function($scope) {
/*...*/
});
据我所知,如果您的项目有不同的部分和不同的依赖项,那么多个模块是一个很好的方法

例如,一个模块在另一个为空时使用
ui.bootstrap
,如:

var firstModule = angular.module('firstModule', []);
var secondModule = angular.module('secondModule', ['ui.bootstrap','firstModule']);
2。两个控制器

var app = angular.module('myApp', []);

app.controller('someCtrl', function($scope) {

     // call other js file:
     otherFile($scope);

    /*....*/
});
app.$inject = ['$scope'];
var otherFile = function($scope) {
/*...*/
});
多控制器方法有助于分割业务逻辑并使代码更清晰

3。两个js文件中的一个控制器

var app = angular.module('myApp', []);

app.controller('someCtrl', function($scope) {

     // call other js file:
     otherFile($scope);

    /*....*/
});
app.$inject = ['$scope'];
var otherFile = function($scope) {
/*...*/
});
您可能希望以这种方式实施(因为我们不知道您的项目目标)

例如:

controllers.js

var app = angular.module('myApp', []);

app.controller('someCtrl', function($scope) {

     // call other js file:
     otherFile($scope);

    /*....*/
});
app.$inject = ['$scope'];
var otherFile = function($scope) {
/*...*/
});
someotherfile.js

var app = angular.module('myApp', []);

app.controller('someCtrl', function($scope) {

     // call other js file:
     otherFile($scope);

    /*....*/
});
app.$inject = ['$scope'];
var otherFile = function($scope) {
/*...*/
});
我认为您应该学习AngularJS中的依赖注入和各种类型的组件。这将使您很好地了解如何将代码库划分为几个层

一小部分最佳实践:

  • 服务-用于将业务逻辑和与API/其他系统的通信保持在一个位置
  • 指令-用于保留直接修改DOM元素的代码
  • 控制器-视图(HTML-DOM)和服务之间的桥梁
  • 模块-较大的功能集可以封装在模块中,这有助于重用较大的组件

查看AngularJs中正确搭建的详细信息。

我认为在我的例子中,我需要将一个控制器拆分为多个js文件。我尝试了您的建议,但出现了一个错误,$scope未定义。我将一个函数从one.js移到two.js。尝试添加'app.$inject=['$scope'];`在定义控制器“我需要将一个控制器拆分为多个js文件”下,请不要!将逻辑提取到多个服务中。您的第二个链接不再工作