AngularJS:模板Url指令无法使用。

问题描述 投票:4回答:7

在过去的一个多小时里,我一直在为一个简单的指令而烦恼。 如果能得到帮助,我将非常感激

我相信hello应该会出现,但似乎不能让它工作?

test.html

   <html>
   <head lang="en">
     <title>Test</title>
   </head>
   <body>
    <div ng-app="myApp">
        <hello></hello>
    </div>


    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
    </body>
  </html>

主.js

    var myApp = angular.module('myApp', []);
    myApp.directive("hello", function() {
     return {
        restrict: 'E'
        templateUrl:"hello.html"
      };
    })`

hello.html

<p>Hello</p>
angularjs
7个回答
15
投票

如果你在本地测试并使用Google Chrome浏览器,那么这将无法工作,因为AngularJS正在对这些html文件进行Ajax调用,但Chrome浏览器以错误阻止了这一点。

XMLHttpRequest cannot load file:/[filepath...] Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

你可以通过打开你的开发者控制台并查看错误来验证这一点。

要绕过这个问题,有几种方法。

  1. 你可以创建一个简单的Web服务器来运行你的代码。如果你有python,你可以直接运行命令(编辑:从你的包含index.html的文件夹)。

    python -m SimpleHTTPServer

  2. 你可以在Chrome中禁用同源策略。https:/stackoverflow.coma60836771100379

  3. 使用Chrome浏览器的一个扩展程序,它可能会帮你做到这一点。我找了一个,这是第一个结果。Allow -Control -Allow -Origin(允许-控制-允许-起源)


9
投票

一切都很好,只要确保你的语法是正确的.不要错过JSON中的逗号。

myApp.directive("hello", function() {
  return {
    restrict: 'E',
                 ^
    templateUrl:"hello.html"
  };
})

演示。http:/plnkr.coeditZ6rjbsuqzmcD4gBem36c。


1
投票

实际上,我们需要为模板Url指令提供相对路径。相对路径完全取决于你提供路径的组件文件。

让我们假设你的文件路径可能是--apphello.html。

那么你的模板Url路径应该是这样的 - templateUrl:".hello.html"


0
投票

打开chrome中的开发工具,进入网络选项卡,找到hello.html的reqest,将reqested路径与服务器上hello.html的路径进行比较。将hello.html移动到合适的位置或更新templeteUrl。


0
投票

打开你的NodeJS命令提示符并安装 http-server 使用 npm install http-server

http-server 是一个简单的零配置命令行http服务器。

安装后,只需使用 http-server -o 在你的NodeJS命令提示符中。


0
投票
  1. 下载Python并将其添加到你的路径环境变量中。

  2. 创建 启动python服务器的cmd文件 在index.html所在的目录下。

2 a) 在与index.html相同的根目录下创建一个新的文本文档。

2 b) write - python -m SimpleHTTPServer 8080。

2 c) 保存为 "所有文件 "类型,并使用一些名称,如startServer .cmd。

  1. 现在已经完成了AJAX调用失败的解决方法。在浏览器中127.0.0.1:8080index.html中显示。

0
投票

你可以在脚本中导入模板,并将其作为 "模板 "使用,而不是 "templateUrl"。

import hello from 'hello.html';
var myApp = angular.module('myApp', []);
myApp.directive("hello", function() {
 return {
    restrict: 'E'
    template: hello
  };
})

0
投票

你可以使用。

userManagementApp.directive("ngCreateUserForm", function () {
    return {
        templateUrl : '/template/create.html'
    };
});

而在服务器端,你必须把你的模板作为静态文件来提供

在围棋中。e.Static("/template", "/path/to/static/folder")或者

在httpd配置中。

Alias /template/ "/path/to/template/folder"
© www.soinside.com 2019 - 2024. All rights reserved.