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?
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) {
/*...*/
});
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:
Have a look this site with details about proper scaffolding in AngularJs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With