【问题标题】:AngularJS Failed to load templateAngularJS 无法加载模板
【发布时间】:2014-12-26 11:56:40
【问题描述】:

我正在尝试使用 AngularJS 指令,这是我的代码:

index.html

<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head>
    <meta charset="UTF-8">
    <title>Directive</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
    <photo photo-src="abc.jpg" caption="This is so Cool" />
</body>
</html>

app.js

var app = angular.module('myapp',[]);

app.directive('photo',function(){
    return {
        restrict: 'E',
        templateUrl: 'photo.html',
        replace: true,
        scope: {
            caption: '@', 
            photoSrc: '@'
        }
    }
});

照片.html

<figure>
    <img ng-src="{{photoSrc}}" width="500px">
    <figcaption>{{caption}}</figcaption>
</figure>

我通过直接在浏览器上打开文件来测试文件。它在 Firefox 上运行良好,但在 IE 和 chrome 上不行。 IE 和 Chrome 都显示错误 Failed to load template

我该如何解决?

【问题讨论】:

  • 查看网络以查看它尝试从哪个路径加载
  • @PSL 它尝试加载的路径是正确的。这是来自 chrome 的错误 Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///E:/www/lab/angularjs/directive/photo.html'.
  • 即因为您尝试使用文件协议加载。不是托管的吗?您可能必须禁用安全性才能加载它......因此缺少来源不是问题。
  • 可能是相关的:我有同样的问题,我确保正确提及模板路径,然后运行“grunt watch”,重要的是构建目录能够构建任何最新文件

标签: javascript angularjs angularjs-directive


【解决方案1】:

您应该从 http 网络服务器调用它,或者您可以在同一个文件中使用如下脚本标签编写模板:

<script type="text/ng-template" id="/tpl.html">
    Content of the template.
</script>

【讨论】:

    【解决方案2】:

    这是 chrome 中的安全问题。 Chrome 不允许跨域请求。 使用 --disable-web-security 启动 chrome

    在 Windows 上:

    chrome.exe --disable-web-security

    在 Mac 上:

    打开 /Applications/Google\ Chrome.app/ --args --disable-web-security

    这将允许跨域请求。请记住,它会禁用网络安全。

    别担心,它会在您托管文件时起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-09
      • 2015-11-15
      • 2018-03-09
      • 2015-02-21
      • 1970-01-01
      • 2013-04-21
      • 2021-05-23
      • 2015-02-09
      相关资源
      最近更新 更多