AngularJS 自定义指令 templateURL

AngularJS Custom Directive templateURL

正在 AngularJS 中创建我的第一个自定义指令,但在使用 templateURL 参数时遇到一些问题;它实际上并没有请求我试图调用的页面。

当我使用普通 template 参数时,它按预期工作。 我想也许我在 templateURL 中使用的路径可能不正确??

这是我的 HTML 在我的主页:

<div class="container" ng-controller="formFields">
    <p>{{person.name}}</p>
    <div ng-sparkline person="person"></div>
</div>

这是我的自定义指令:

myApp.directive('ngSparkline', function() {
  return {
    replace: true,
    restrict: 'EA',
    scope: {
        person: '='
    },
    //template: '<p class="lead">Hi, {{person.name}}!</p>'
      templateURL: '/js/directives/formFields.html'
  }
});

这是我的 formFields.html 文件:

<p class="lead">Hey, {{person.name}}</p>


我的应用程序目录是这样布局的: 我的 directives.js 文件位于 js 目录,而 formFields.html 文件位于 /js/directives/...

您有一个拼写(大小写)错误。 templateUrl,不是templateURL

首先,您将 templateUrl 错写为 templateURL。 如果这不能解决您的问题,可能是因为绝对 URL.

您是通过服务器提供文件还是通过磁盘在浏览器中打开它?

如果您的 link 是 file://C://www/html/js/directives,绝对路径 /js/directives 目标 file://C:/js/directives,显然没有模板代码所在。在这种情况下,您需要使用相对路径。