0

I'm using Angular for front end use, and I'm trying separate my application per modules.

For organization, I want separate one module per file and all your controllers is a file to, file structure example:

- module1 (paste)
    - controllers (paste)
        - controller1.js
        - controller2.js
    - module.js

Where module1.js require controller1.js and controller2.js, and main javascript file require all modules file.

For controllers, I'm module.exports only content of controller, something like:

// controller1.js
module.exports = ["$scope", function(scope) {
  // some code here
}];

In my module file, I require it this way:

//module1.js
var app = angular.module("module1", []);

app.service("service1", function() {});

app.controller("controller1", require("./controllers/controller1.js");
module.exports = app;

Until this point, is allright.

But when I try require module1.js to module2.js for use service1, this is return service1 is not defined.

//module2.js
require('../module1/module.js');

var app = angular.module("module2", ['module1']);
app.controller('controller2-1', ["$scope", "service1", function(scope, service1) {
    // some code
});

What is correct way to separate modules per file and require it with Browserify?

1 Answer 1

1

try this:

//child module
var angular = require('angular');
var moduleName = 'moduleChild';
var moduleDependencies = [...];

app.module(moduleName, moduleDependencies)
   .controller('foobarctrl', [function(){}]);

module.exports = moduleName;

//parent module
var angular = require('angular');
var moduleChild = require('/path/to/file');
var moduleName = 'moduleChild';
var moduleDependencies = [moduleChild];

app.module(moduleName, moduleDependencies)
   .controller('foobarbazctrl', [function(){}]);

module.exports = moduleName;

This way is one of the most cleaner way to use angular with browserify, it is not usefull to exports the module1 object because you don't wan't to reuse it, you just need there name.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.