Loading ng-include partials from local pre-loaded (JST) template cache

扶醉桌前 提交于 2019-12-03 20:06:15

Here is the solution I found to work, and it's not a hack like I was thinking earlier (above :-) Basically, decorate the $templateCache.get method using standard $provide.decorator so that cache gets look in my local pre-loaded cache. It just works.

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;
  }
]);

If you're wondering why I have this stuff in JST, we use a rails backend and the rails asset pipeline to deliver all angular assets. The JST templates allow us to bundle all templates and load them into the app during initialization, and avoid additional server roundtrips that are normally required when fetching partials and other template content.

The above patch makes all of this works with angular.

Instead of ng-include, use ng-bind-html:

<div ng-bind-html="t"></div>

On your controller, place the template on the $scope:

$scope.t = JST['firstTemplate'];

You will need to include ngSanitize as a submodule (don't forget to add angular-sanitize.js too):

angular.module('app', ['ngSanitize']);

today i am faced with the same problem, here is my solution:

A custom directive, which return the JST"server/info" as template:

/* jstTemplate.js */

/**
 * @desc template loader for JST templates
 * @example <div jst-template="server/info.html"></div>
 */


angular
    .module('myApp')
    .directive('jstTemplate', jstTemplate);

function jstTemplate() {
    return {
        restrict: 'A',
        template: function(element, attrs) {
            return JST[attrs.jstTemplate]();
        }
    }
};

Usage:

<div class="box">
    <div jst-template="server/info.html"></div>
</div>

The attrs.jstTemplate contains the value, we provided in the directive.

Cheers, Niklas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!