Search code examples
angularjsangularjs-directiveangularjs-ng-includemeanjs

How to dynamically include all template partials when using a module in AngularJS


I have several modules that require some template partials to be loaded whenever the module is used. I am storing these files in a folder called partials inside each module subfolder. My starting point for my app is meanjs, and I am storing partials file are in public/modules//partials/*.html.

I have seen several ng-include and directive examples, but being new to AngularJS each sample I read confuses me further as to what is best practice / most AngularJS appropriate way to do this.


Solution

  • Store your partials whenever you wants. To load them all use angular template cache.

    Use Grunt or gulp to generate automatically. Personally I use gulp.

    Here is my working example of one of my project.

    install nodejs and npm

    npm intall gulp -g

    npm install gulp-angular-templatecache

    create gulpfile.js

    var templateCache = require('gulp-angular-templatecache'),
        watch = require('gulp-watch');
    
    gulp.task('generate', function () {
        gulp.src('public/*/partials/*.html')
            .pipe(templateCache('templates.js', {module: 'YOURMODULENAME', standalone: false}))
            .pipe(gulp.dest('public/js'));
    });
     gulp.task('watch-partials', function () {
        gulp.watch('public/*/partials/*.html', ['generate']);
    });
    

    then use it like this:

    gulp generate - to regenerate partials

    gulp watch-partials - watch file changes, if partials are changed it automatically run generate task for you. :)

    One more thing, dont forget to include template.js in your html file

    <script src="public/js/template.js"></script>

    Every time you change your partial dont forget to regenerate your template cache.