在Angular $templateCache中使用和注入RequireJS

Using and injecting Angular $templateCache with RequireJS

本文关键字:注入 RequireJS Angular templateCache      更新时间:2023-09-26

我做了一个grunt serve:dist,在我基于我的RequireJS main.js文件构建grunt-contrib-requirejsall.js文件,其中有require.configrequire部分。

我认为all.js应该在我的发行文件中我必须在启动时包含在我的index。html中,因为所有东西都在那里。这样对吗?

<script src="require.js" data-main="all.js"></script>

我还基于我所有的模板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
  }]);
});

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

我有类似的问题,我找到了一个方法来解决它。基本上,我有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);
})

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