Javascript 将模板从src转换为变量

Javascript 将模板从src转换为变量,javascript,html,angularjs,angularjs-routing,Javascript,Html,Angularjs,Angularjs Routing,我想将模板的内容加载到变量中。目前我的代码是这样的 HTML <script type="text/ng-template" id="a.html" src="templates/a.html"></script> 这应该将“templates/a.html”的内容加载到vm.template中。遗憾的是,这不起作用。变量vm.template不包含该模板 我在测试时发现,如果我像这样将模板的内容直接写入脚本标记中 <script type="text/ng-t

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

HTML

<script type="text/ng-template" id="a.html" src="templates/a.html"></script>
这应该将“templates/a.html”的内容加载到vm.template中。遗憾的是,这不起作用。变量vm.template不包含该模板

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

<script type="text/ng-template" id="a.html">Hello!</script>
你好!
它确实有效


在ng模板上使用src可能不起作用:

您可以使用ng,包括:

<script type="text/ng-template" id="a.html">
    <div ng-include="'templates/a.html'"></div>
</script>
此外,它们也会向您的服务器发出请求(确保您已配置了静态数据)

您可以使用指令:

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

这是个问题吗?@Rohit是的。它在标题中这样说,我想从源代码而不是从脚本标记内部将内容加载到变量中。您应该检查这个
.config(function ($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: 'templates/a.html',
            controller: 'aController'
        }).when("/second", {
            templateUrl: 'templates/b.html',
            controller: 'bController'
        }).otherwise({redirectTo: "/"});
});
.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);
        });
      }
    };
  })