ng-template to src中的变量

时间:2016-07-25 07:07:59

标签: javascript html angularjs angularjs-routing

我想将模板的内容加载到变量中。目前我的代码看起来像这样。

HTML

<script type="text/ng-template" id="a.html" src="templates/a.html"></script>

JS

vm.template = $templateCache.get('a.html');
console.log("Template: " + vm.template);

这应该加载&#39; templates / a.html&#39;的内容。进入vm.template。可悲的是,这不起作用。变量vm.template不包含模板。

The variable does not contain the template

我在测试时发现的是,如果我将模板的内容直接写入脚本标签中

<script type="text/ng-template" id="a.html">Hello!</script>

它确实有效。

The variable contains the template

2 个答案:

答案 0 :(得分:3)

在ng-template上使用src可能不起作用:

您可以使用ng-include:

<script type="text/ng-template" id="a.html">
    <div ng-include="'templates/a.html'"></div>
</script>

或在路由配置中执行此操作:

.config(function ($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: 'templates/a.html',
            controller: 'aController'
        }).when("/second", {
            templateUrl: 'templates/b.html',
            controller: 'bController'
        }).otherwise({redirectTo: "/"});
});

此外,它们会向您的服务器发出/templates/a.html GET请求(请确保您已配置静态)

答案 1 :(得分:0)

你可以使用指令:

.directive('script', function() {
    return {
      restrict:'E',
      scope: false,
      controller: function($attrs, $templateCache, $http, $log) {
        if($attrs['type'] != "text/ng-template" || !$attrs['src']){
          return;
        }

        var id = $attrs['id'] || $attrs['src'];
        var src = $attrs['src'];
        $log.debug('Loading %s template from %s', id, src);

        $http.get(src).then(function(response){
          $log.debug('Loaded template %s', id);
          $templateCache.put(id, response.data);
        });
      }
    };
  })