Skip to content Skip to sidebar Skip to footer

Angular Js Seperation To Different Modules In Different Js Files

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

Solution 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:

varfirstModule= angular.module('firstModule', []);
varsecondModule= 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:

varfirstModule= angular.module('firstModule', []);
varsecondModule= 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) {
/*...*/
});

Solution 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.

Post a Comment for "Angular Js Seperation To Different Modules In Different Js Files"