Frage

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

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.

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

War es hilfreich?

Lösung

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

It is good example to start with.

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>

Andere Tipps

There are a few conventions out there and it doesn't really appear that any "best practice" has emerged yet.

That being said, the two conventions that I like put each controller/filter/service/etc in their own directory. As far as directory structure, for smaller projects I've seen a directory for each type of file. For large projects, I've seen a directory for each module with all controllers/filters/services for that module in that folder. This also forces you to split your app up into modules which is a nice side effect.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top