使用和注入Angular $templateCache与RequireJS

5
我运行了grunt serve:dist,在其中使用grunt-contrib-requirejs来构建一个基于我的RequireJS main.js文件的all.js文件,其中包含了require.configrequire部分。我认为all.js应该在我的发布版本中,因为它包含了所有的内容,我需要在index.html中启动时引入它,这样对吗?
<script src="require.js" data-main="all.js"></script>

我还会基于所有模板 HTML 文件创建一个带有 ngTemplates 的模板 JavaScript 文件,并对其进行引导,以便模板文件命名为 templates.js,如下所示:

define([
  'angular'
], function(angular) {
  angular.module('MyApp.templates', []).run(['$templateCache', function($templateCache) {
    'use strict';
    $templateCache.put('templates/MyTest.html',
      "<h1>Title</h1>\r" +
      // ...
    // other put on $templateCache
  }]);
});

我有一个名为$templateCache的缓存,我想要使用它。但是我不知道该怎么做。我认为我需要加载templates.js,因为它没有包含在all.js中,所以我应该用某种方式注入它。

1个回答

0
我曾遇到类似的问题,并找到了解决方法。基本上,我有一个名为templates.js的文件,它只返回一个函数以注入到运行块中。
例如:templates.js
define([], function()){
    return ['$templateCache", function($templateCache){
        'use strict';
        $templateCache.put('templates/MyTest.html',
        "<h1>Title</h1>\r" +
        // ...
        // other put on $templateCache
    }];
}

然后,在您的app.js文件中,您可以将此函数注入到运行块中。

define(['templates'], function(templates){
    angular.module('app')
        .run(templates);
})

希望这对你有所帮助,请告诉我如果有什么不清楚的地方。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接