2

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

为了完整和后代,这里的代码:

你好.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>
4

2 回答 2

2

当我运行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 错误参考文档说,

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

通常,如果您尝试从不受信任的来源加载 Angular 模板,就会发生这种情况。自定义指令也可能出于类似原因引发此错误。

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

于 2014-07-20T15:22:11.123 回答
1

将其放在 HTML 的顶部(在加载 Angular 的脚本标记之后):

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

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

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

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

于 2014-07-20T14:43:54.700 回答