I am building a small angular app with browserify and ui-router. As I don't want to use a server, I want to store all my templates using angular's $templateCache like this:
exports.templateCache = ["$templateCache", function($templateCache) {
  'use strict';
  $templateCache.put('partials/someState.html',
    "myHtmlCode"
  );
}];
To populate the cache, I use grunt to look into my partials folder, grab all the html and load it into the cache with grunt-angular-templates:
 ngtemplates:  {
  myApp: {
    cwd: 'dist/',
    src: 'partials/**.html',
    dest: 'src/js/templates/templates.js',
    options: {
      bootstrap:  function(module, script) {
        return 'exports.templateCache = ["$templateCache", function($templateCache) {\n' +
          script +
          '}];'
      }
    }
  }
},
I then use browersify to combine all my js together:
browserify: {
  dist: {
    files: {
      'dist/js/app.js': [
          'src/js/templates/**',
          'src/app.js'
          ],
    }
  }
},
This is working so far but this workflow looks very unwieldy to me: I have an intermediary step where I create the templates.js file in my src directory and I have hard-coded code in my grunt file. 
Is there any way to do this more elegantly? Does browserify come with built in solutions to tackle this problem?
- service in module ng Overview $templateCacheis a Cache objectcreated by the $cacheFactory. The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a scripttag, by using $templateRequest, or by consuming the $templateCacheservice directly.
Overview $templateCacheis a Cache objectcreated by the $cacheFactory. The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a scripttag, by using $templateRequest, or by consuming the $templateCacheservice directly.
The best way to use $templateCache is to integrate it into your build process, for example by using the gulp plugin gulp-angular-templatecache. The following gulp task creates a module where all template files were registered in the $templateCache.
For applications using Angular 2 or higher, there is a special loader, called angular2-template-loader, that inlines all template code into the corresponding angular components. In your webpack.config.js, you add the angular2-template-loader to your current typescript loader. Furthermore, you need to define a loader that can process html files.
browserify-ng-html2js has been designed to resolve this problem.
Simply add in package.json :
"browserify": {
    "transform": ["browserify-ng-html2js"]
 }
And you'll see if it walks the talks :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With