从本地预加载(JST)模板缓存加载ng-include部分

Shy*_*ada 4 jst angularjs angularjs-ng-include angular-template

我将我的模板预先加载到一个javascript字符串数组中,就像var t = JST['firstTemplate']在哪里t一样,

<div>This scope has a value of {{value}}</div>
Run Code Online (Sandbox Code Playgroud)

如何在ng-include指令中使用此预加载的模板?

请注意,此场景中的模板可能更复杂,可能具有嵌套视图和模板以及它们自己的嵌套作用域和控制器.所以我不确定任何ng-bind指令是否有帮助?

更新:

查看ng-include它的来源似乎是一种很好的方法,可以将模板加载逻辑解耦为可自定义的提供程序.

当前的默认加载机制只是做了$http.get$templateCache作为缓存提供者.看起来我可以将模板内容注入JST['firstTemplate']到模板缓存中,但是我必须在启动时为每个模板执行此操作.

$templateCache.put('firstTemplate', JST['firstTemplate']);
Run Code Online (Sandbox Code Playgroud)

然后有,

<div ng-include="firstTemplate"></div>
Run Code Online (Sandbox Code Playgroud)

我还可以编写一个与每个ng-include并排的自定义指令,它以某种方式预先缓存模板.这再次显得笨重.

更新#2

我将尝试重写templateCache,以便它使用我已经预先加载的JST哈希.如果有效,将发布结果.

Shy*_*ada 6

这是我发现工作的解决方案,它不像我之前想的那样(上面:-)基本上,使用标准的$ provide.decorator装饰$ templateCache.get方法,以便缓存在我的本地预加载中查找缓存.它只是有效.

angular.module('app').config([
  '$provide', 
  function($provide) {
    $provide.decorator('$templateCache', function($delegate, $sniffer) {
      var originalGet = $delegate.get;

      $delegate.get = function(key) {
        var value;
        value = originalGet(key);
        if (!value) {
          // JST is where my partials and other templates are stored
          // If not already found in the cache, look there...
          value = JST[key]();
          if (value) {
            $delegate.put(key, value);
          }
        }
        return value;
      };

      return $delegate;
    });

    return this;
  }
]);
Run Code Online (Sandbox Code Playgroud)

如果你想知道为什么我在JST中有这些东西,我们使用rails后端和rails资产管道来提供所有角度资产.JST模板允许我们捆绑所有模板并在初始化期间将它们加载到应用程序中,并避免在获取部分内容和其他模板内容时通常需要的其他服务器往返.

上面的补丁使得所有这些都适用于角度.