4
\$\begingroup\$

My intention is to separate components on a file basis. For example, I want a specific controller to have it's own file (Same goes with services, filters and directives). Of course, files will be group together based on the module they will fall into.

Here's an overview of what I currently have:

Directory

User/
    User/UserModule.js
    User/UserDirective.js
    User/UserService.js
    User/UserFilter.js
    User/UserController.js

UserModules.js

UserModule = angular.module('UserModule', []);

UserModule.controller('userCtrl', ['$scope', 'UserService', UserCtrl])

    .factory('userService', function() {
        return new UserService();
    })  

    .filter('userFilter', UserFilter)

    .directive('userDirective', UserDirective);

UserController.js

UserCtrl = function($scope, UserService) {
    // ...
};

UserDirective.js

UserDirective = function() {
    return {
        // ...
    }
};

UserService.js

UserService = function() {
    // ...
};

UserFilter.js

UserFilter = function() {
    return function() {
        // ...
    }
};

Then I'll just push the user module to the app module.

app.requires.push('UserModule');

My concern lies on the registration of the concepts (Such as controllers, services...) to the module. I was wondering if this is the best way to go and if it's correct. Also possible issues on the parameters and the external .js file.

Consider this part:

.controller('userCtrl', ['$scope', 'UserService', UserCtrl])

The UserCtrl above refers to a function defined in a separate file. Will I be able to pass the $scope and UserService dependency as parameters to the UserCtrl?

UserCtrl = function($scope, UserService) { // Pass parameters (UserController.js)

What's the correct way of doing this in terms of Services, Filters and Directives?

Finally, how can I improve the code?

\$\endgroup\$
  • \$\begingroup\$ I would organise the files exactly as you have done: functional. Otherwise the components that works together are split around and are likely not so easy available for reuse. More arguments can be found in the www: henriquat.re/modularizing-angularjs/… \$\endgroup\$ – dec Jan 11 '15 at 12:50
2
\$\begingroup\$

It would be much easier to give feedback if we saw your actual code, for those 5 js files.

Regardless, I tend to organize differently:

controllers/
  user.js
views/
  user.js
models/
  user.js

So anything that does not fit controller/user.js or views/user.js goes into models/user.js.

I want a specific controller to have it's own file (Same goes with services, filters and directives). There is no good enough reason to do this, keep controllers and views together, and do not split up everything.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.