【问题标题】:Demo of an AngularJS directive's templateUrl in JsBinJsBin 中 AngularJS 指令的 templateUrl 演示
【发布时间】:2014-07-20 23:28:05
【问题描述】:

我有我想用 JsBin 演示的工作代码,但我无法让 AngularJS 指令 templateUrl 工作(它确实与 template 值一起工作)。 http://jsbin.com/guvok/ 试图引用 http://jsbin.com/razit/ 但失败了。

为了完整起见,代码如下:

hello.html

<!DOCTYPE html>
<html ng-app="hello">
<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
</head>
<body>
  <div hello></div>
</body>
</html>

你好.css

.hello__content {
    background: #fff;
  }

你好.js

var meter = angular.module('hello', [])
  .directive( 'hello', function() {
    return {
      restrict: 'A',
      replace: true,
      //template: '<p class="hello__content">hello</p>',
      templateUrl: 'http://jsbin.com/razit/',
    };
  });

模板.html

<p>hello, world</p>

【问题讨论】:

  • 在控制台中查看错误,你可能想将模板js添加到index.html

标签: angularjs-directive jsbin


【解决方案1】:

当我运行 http://jsbin.com/guvok/ 时,我在浏览器的 Javascript 控制台中收到以下错误:

Error: [$sce:insecurl] http://errors.angularjs.org/1.2.19/$sce/insecurl?p0=http%3A%2F%2Fjsbin.com%2Frazit%2F

如果您查找“$sce:insecurl”,您会发现 AngularJs error reference doc 上面写着,

AngularJS 的严格上下文转义 (SCE) 模式(默认启用) 已阻止从不安全的 URL 加载资源。

通常,如果您尝试加载 Angular 来自不受信任的来源的模板。也有可能是自定义 指令出于类似的原因抛出此错误。

它还提供了一些解决问题的方法,这本质上是一个 CORS 问题。

【讨论】:

    【解决方案2】:

    把它放在 HTML 的顶部(在加载 Angular 的脚本标签之后):

    <script type="text/ng-template" id="templateURL">
      <!-- TEMPLATE MARKUP GOES HERE -->
    </script>
    

    编辑:在您的情况下,ID 将是“http://jsbin.com/razit/”,这样您就不必编辑指令。最坏的情况,将 templateURL 更改为不引用外部 jsBin。

    编辑 #2: 将 templateUrl 更改为字符串值 not 引用外部 url 或使用 http 协议,我现在可以在 jsBin 编辑模式下看到您的输出。

    jsBin 在这里:http://jsbin.com/dutofete/1/

    【讨论】:

    • 你有没有得到任何控制台输出的代码?
    • 转到您刚刚指定的网址(不是在编辑模式下)我可以清楚地看到“你好,世界”的输出。这不是您所期待的吗?
    • 查看我的最新编辑以获取工作示例。很可能,它与 GreyBeardedGeek 指出的交叉引用有关。
    猜你喜欢
    • 2016-04-24
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 2013-01-23
    相关资源
    最近更新 更多