【问题标题】:ng-template to Variable from srcng-template 到来自 src 的变量
【发布时间】:2016-07-25 07:07:58
【问题描述】:

我想将模板的内容加载到变量中。目前我的代码如下所示。

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

这应该将 'templates/a.html' 的内容加载到 vm.template 中。可悲的是,这不起作用。变量 vm.template 不包含模板。

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

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

它确实有效。

【问题讨论】:

标签: javascript html angularjs angularjs-routing


【解决方案1】:

在 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 请求(确保您已配置静态)

【讨论】:

    【解决方案2】:

    你可以使用指令:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多