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

Tim*_*Tim 5 javascript requirejs angularjs gruntjs

我在一个grunt serve:dist内部构建了grunt-contrib-requirejs一个all.js基于我的RequireJS main.js文件的文件,该文件有require.config一个require部分.

我认为all.js应该在我的发行版中,我必须在我的index.html中包含启动时包含的文件,因为一切都在那里.这是正确的吗?

<script src="require.js" data-main="all.js"></script>
Run Code Online (Sandbox Code Playgroud)

我还基于我的所有模板HTML文件创建了一个模板JavaScript文件,ngTemplates并使用它来引导它,因此名为的模板文件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
  }]);
});
Run Code Online (Sandbox Code Playgroud)

所以我有一个$templateCache我想要使​​用的.但我不知道如何做到这一点.我想我必须加载templates.js因为它不包含在内all.js,因此我应该以某种方式注入它.

Ku *_*hin 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
    }];
}
Run Code Online (Sandbox Code Playgroud)

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

define(['templates'], function(templates){
    angular.module('app')
        .run(templates);
})
Run Code Online (Sandbox Code Playgroud)

我希望这对您有所帮助,如果您有任何不清楚的地方,请告诉我。