简体   繁体   中英

Best practice of angular code structuring

The problem is I don't know if it's viable in Angular.JS to place every separate code entity (controller, model, service etc) in a separate .js file. I'm trying to implement my solution this way at the moment, but it just doesn't feel right.

Example:

step.js content (model prototype):

(function() {
    var moduleStep = angular.module('step', []);
    moduleStep.config(function() {
        var defaults = {
            title: "",
            enabled: true,
            active: false,
            visited: false,
            viewUrl: "/clientTemplates/notification/step1.html",
            model: {}
        };

        /**
         * @param {string} title
         * @param {string} viewUrl
         * @param {object} model   [optional]
         * @constructor
         */
        moduleStep.Step = function(title, viewUrl, model) {
            _.extend(this, defaults);
            this.title = title;
            this.viewUrl = viewUrl;
            _.isUndefined(model) && (this.model = model);
        };
        var prot = moduleStep.Step.prototype;

        /**
         * @returns {boolean}
         */
        prot.isValid = function () {
            return true;
        }
    });
}());

masterController.js content (controller):

(function() {
    var moduleController = angular.module('masterController', [
        'ui.bootstrap',
        'step',
        'config'
    ]);

    moduleController.config(function() {
            var Step = angular.module('step').Step;

            /**
             * @type {Array}
             */
            $scope.steps = [
                new Step("step 1", "/clientTemplates/notification/step1.html"),
                new Step("step 2", "/clientTemplates/notification/step2.html", {test2: 2}),
                new Step("step 3", "/clientTemplates/notification/step3.html", {test: 1})
            ];
        };
        controller.$inject = ['$scope'];

        moduleController.masterController = controller;
        console.log(moduleController.masterController);
    });
}());

setupMaster.js (application module)

(function() {
    var app = angular.module('setupMaster', [
//    'ngRoute',
        //controllers
        'masterController',
        'config'
    ]);


    /**
     * Конфигурационная функция для провайдеров служб приложения
     */
    app.config(['$controllerProvider', '$httpProvider', function($controllerProvider, $httpProvider) {
        $controllerProvider.register('MasterController', angular.module('masterController').masterController);
    }]);
}());

http://docs.angularjs.org/guide/module

In the "recommended setup" block it is written that 4 large modules should be used for services, directives, filters and the application layer. What about controllers or models factories/prototypes?

Maybe it's just me being stupid or not compatible with Angular's paradigm, but module and injectors systems in Angular seem a bit over-engineered and counter-intuitive. Though i really like Angular's 2-way data binding and dirty-checking instead of callbacks.

I've been trying to find best practices and justifications over reasons. In addition to reading angular docs, other article.. I found JohnPapa's description and in-depth explanation gives a little more insight of why's and why-not's, do's and don'ts. Read it here

Like others suggested, do checkout angular-seed and other ng-generators etc. Eventually, it is where you are comfortable with the right practices which evolves over time.

No rights or wrongs because they all have valid points. ie. testability, dependency injection, minification, optimization.. etc.

Just to share..

Im working with w11k Fabs wich is a basic grunt setup with stuff like livereload/jshint/sass,less/testing/ngannotate...

The setup is view/route-orientated. Means the views/route are in a hierarchic foulder structure. For every view/route a new module and ctrl file. fabs handles to link them in your index file. since service are used in several views they are stored in a seperate folder.

if you "grunt dist" your project everything is minified into 1 file.

try: https://www.npmjs.com/package/fabs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM