简体   繁体   English

角度代码结构的最佳实践

[英]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. 问题是我不知道在Angular.JS中将每个单独的代码实体(控制器,模型,服务等)放置在单独的.js文件中是否可行。 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): step.js内容(模型原型):

(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): masterController.js内容(控制器):

(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) setupMaster.js(应用程序模块)

(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 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. 在“推荐的设置”块中,写道,应将4个大模块用于服务,指令,过滤器和应用程序层。 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. 也许只是我愚蠢或与Angular的范式不兼容,但是Angular中的模块和注入器系统似乎有点过分设计且违反直觉。 Though i really like Angular's 2-way data binding and dirty-checking instead of callbacks. 虽然我真的很喜欢Angular的2路数据绑定和脏检查而不是回调。

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. 除了阅读有角度的文档外,其他文章..我发现JohnPapa的描述和深入的解释使您对为什么和为什么不做什么,不应该做什么有更多的了解。 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. 像其他建议的一样,请检查角度种子和其他ng生成器等。最终,您会随着时间的推移适应正确的做法。

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... 我正在使用w11k Fabs工作,这是一个基本的grunt设置,其中包含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. 对于每个视图/路线,都有一个新的模块和ctrl文件。 fabs handles to link them in your index file. fabs句柄将它们链接到索引文件中。 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. 如果您“ grunt dist”您的项目,则所有内容都将压缩为1个文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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