Structuring my AngularJS application

后端 未结 5 1735
旧巷少年郎
旧巷少年郎 2021-01-30 10:57

I\'m totally newbie at using AngularJs and although I\'ve been through the tutorials, I still have loads of unanswered questions in my mind. My main concern right now is how sho

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 11:40

    [EDIT] I wrote an article on my blog to explain things in more details:

    read it on sam-dev.net and you can now read part II, with code sample.

    I'll answer my own question. Not because I think it's the best approach, but just because it's the one I've decided to go with.

    This is how I've divided my business modules into folders

    • app
      • businessModule
        • controllers
          • index.js
          • firstCtrl.js
          • secondCtrl.js
        • directives
        • services
        • views
        • filters
      • anotherBusinessModule
      • shared
      • app.js
      • index.html

    Each module has its own folder structure for controllers, directives, etc...

    Each folder has an index.js file and then other files to separates each controller, each directive, etc...

    The index.js file contains the definition of the module. For instance for the controllers of the businessModule above:

    angular.module('myCompany.businessModule.controllers', []);
    

    There's no dependencies here, but there could be any.

    Then in firstCtrl.js, I can reuse that module and add the controller to it:

    angular.module('myCompany.businessModule.controllers').controller('firstCtrl',     
    
            function(){
    });
    

    Then the app.js aggregates all the module that I want for my application by adding them to the dependencies array.

     angular.module('myApp', ['myCompany.businessModule', 'myCompany.anotherBusinessModule']);
    

    The shared folder contains directives and other things that are not specific to a business module and that can be reused anywhere.

    Again, I don't know if it's the best approach, but it definitely works for me. Maybe it can inspire other people.

    EDIT

    As the index.js files contain modules declarations, they must be referenced in the html page before any other application scripts. To do so, I've used the IBundleOrderer of ASP.NET MVC 4:

     var bundle = new ScriptBundle("~/bundles/app") { Orderer = new AsIsBundleOrderer() };
     bundles.Add(bundle.IncludeDirectory("~/app", "*.js", true));
    
    public class AsIsBundleOrderer : IBundleOrderer
    {
        public IEnumerable OrderFiles(BundleContext context, IEnumerable files)
        {
            files = files.OrderBy(x => x.Name == "index.js" ? 0 : 1);
            return files;
        }
    }
    

提交回复
热议问题