Angular js分离到不同js文件中的不同模块 [英] Angular js seperation to different modules in different js files

查看:22
本文介绍了Angular js分离到不同js文件中的不同模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个支持拖放元素的 Angular Web 应用程序.

I created an angular web application that enables drag and drop elements.

我完成了它的构建,但我有一个大模块.该模块被放置在一个包含数千行代码的 js 文件中.

I finish building it, but i have one big module. The module is placed in one js file with thousand of code lines.

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

I would like to know how can i separate my big modules to several modules in several js files that communicate with each other.

有人可以给我提供一个简单的例子,我该怎么做?

May someone provide me simple example how can i do it?

推荐答案

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

I would like to know how can i separate my big modules to several modules in several js files that communicate with each other.

当然,您可以使用多个模块并将它们绑定,如下例所示:

Sure you can use several modules and bind them like in following example:

var firstModule = angular.module('firstModule', []);
var secondModule = angular.module('secondModule', ['firstModule']);

现在在 firstModule 中创建的所有服务/指令都在 secondModule 中可见.

Now all services/directives created in firstModule are visible in secondModule.

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

But before you create two modules you should ask yourself:

1.两个模块

据我所知,如果您的项目具有不同依赖项的不同部分,那么使用多个模块是个好方法.

Multiple modules as I know is good way if your project has different sections with different dependencies.

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

For example one module uses ui.bootstrap when other is empty, like:

var firstModule = angular.module('firstModule', []);
var secondModule = angular.module('secondModule', ['ui.bootstrap','firstModule']);

2.两个控制器

多控制器方式有利于拆分业务逻辑并使代码更清晰

The multiple controller approach is good to split business logic and make code clearer

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

您可能希望以这种方式实施(因为我们不知道您的项目目标)

You would want to implement this way (since we don't know your project goals)

例如:

controllers.js

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

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

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

    /*....*/
});
app.$inject = ['$scope'];

someotherfile.js

var otherFile = function($scope) {
/*...*/
});

这篇关于Angular js分离到不同js文件中的不同模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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