使用和注入带有RequireJS的Angular $ templateCache

时间:2014-08-21 11:57:19

标签: javascript angularjs requirejs gruntjs

我执行了grunt serve:dist并且使用grunt-contrib-requirejs all.js基于我的RequireJS main.js文件构建了require.config文件,该文件具有require和{{1} }。section。

我认为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 :(得分: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);
})

我希望这有帮助,如果您对某些事情不清楚,请告诉我。