使用带有browserify的角度模板缓存

时间:2014-10-22 07:54:31

标签: javascript angularjs caching gruntjs browserify

我正在使用browserify和ui-router构建一个小角度应用。由于我不想使用服务器,我想使用角度$templateCache存储我的所有模板,如下所示:

exports.templateCache = ["$templateCache", function($templateCache) {
  'use strict';

  $templateCache.put('partials/someState.html',
    "myHtmlCode"
  );
}];

要填充缓存,我使用grunt查看我的partials文件夹,获取所有html并使用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 +
          '}];'
      }
    }
  }
},

然后我使用browersify将我所有的js组合在一起:

browserify: {
  dist: {
    files: {
      'dist/js/app.js': [
          'src/js/templates/**',
          'src/app.js'
          ],
    }
  }
},

这个工作到目前为止,但这个工作流对我来说看起来非常笨拙:我有一个中间步骤,我在templates.js目录中创建src文件,我的grunt中有硬编码的代码文件。

有没有办法更优雅地做到这一点? browserify是否附带内置解决方案来解决这个问题?

2 个答案:

答案 0 :(得分:3)

browserify-ng-html2js旨在解决此问题。

只需添加package.json:

"browserify": {
    "transform": ["browserify-ng-html2js"]
 }

你会看到它是否走过谈判:)

答案 1 :(得分:0)

尝试使用browserify进行转换,以便您可以使用html文件(例如Stringify)。然后你可以要求('yourPartial.html')作为字符串:

$templateCache.put('yourPartialId', require('./partials/yourPartial.html'));

// html file
<div ng-include=" 'yourPartialId' "></div>