Angular js seperation to different modules in different js files [closed]

瘦欲@ 提交于 2019-12-23 19:23:47

问题


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

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

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?


回答1:


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']);

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

But before you create two modules you should ask yourself:

1. two modules

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

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. two controllers

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

3. one controller in two js files

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

For example:

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) {
/*...*/
});



回答2:


I think you should follow the official Angular tutorial to learn about the dependency injection and various types of components available in AngularJS. That will give you a good overview of how to split your code base into several layers.

A small set of best practices:

  • Services - are used to keep the business logic and communication with APIs/other systems in one place
  • Directives - are used to keep the code which modifies the DOM elements directly
  • Controllers - a bridge between the view (HTML - DOM) and services
  • Modules - larger sets of features can be encapsulated in module, which helps to reuse larger components

Have a look this site with details about proper scaffolding in AngularJs.



来源:https://stackoverflow.com/questions/20836561/angular-js-seperation-to-different-modules-in-different-js-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!