AngularJS约定多个文件多个、文件、AngularJS

2023-09-13 04:52:29 作者:︶ ̄冷情绪╮雪儿控︶

如果有避免在AngularJS单片js文件的最佳实践我想知道。

I was wondering if there are best practices for avoiding monolithic js files in AngularJS.

我想避免非常大的controllers.js / filters.js / services.js文件。相反,管理的缘故,我想有每个控制器/过滤/服务在它自己的文件。

I would like to avoid having very large controllers.js/filters.js/services.js files. Instead, for the sake of manageability, I would like to have each controller/filter/service in its own file.

我想知道,如果有这种方法尽可能的目录结构推荐的惯例和命名约定关注。

I would like to know, if there is a recommended convention for this approach as far as the directory structure and naming convention is concerned.

此外,什么可能是为了避免我的应用程序/ index.html中添加脚本标签为每个新文件创建的最佳方式?

Also, what might be the best way to avoid adding a script tag in my app/index.html for each new file I create?

推荐答案

您可以检查这个程序: https://github.com/angular-app/angular-app

You may check this app: https://github.com/angular-app/angular-app

这是很好的例子开始。

此外,什么可能是为了避免我的应用程序/ index.html中添加脚本标签为每个新文件创建的最佳方式?

Also, what might be the best way to avoid adding a script tag in my app/index.html for each new file I create?

它可以通过咕噜例如观察家自动化。我用这样的配置此任务:

It can be automated by grunt watcher for example. I use such a config for this task:

grunt.initConfig({
    index: {
        files: ['app/js/**/*.js'],
        tasks: 'index:scripts'
    }
})

grunt.registerMultiTask('index', 'Create index.html',
        function() {        
            var files = grunt._watch_changed_files || grunt.file.expand(this.data);
            var now = new Date().getTime();
            var scripts_str = '';
            var tpl = grunt.file.read('app/index.html.tmpl');


            files.forEach(function(file) {
                file = file.replace(/^app\//, '');
                scripts_str += '<script src="' + file + '?bust=' + now + '"></script>' + "\n";
            });   

            grunt.file.write('app/index.html', grunt.template.process(tpl, {
                data: {
                    scripts: scripts_str
                }
            }))
            console.log('File "index.html" created.');

        });

的 index.html.tmpl 的:

<html>
<body>
    ...
    <%=scripts%>
</body>
</html>