在过去的一个多小时里,我一直在为一个简单的指令而烦恼。 如果能得到帮助,我将非常感激
我相信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>
如果你在本地测试并使用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.
你可以通过打开你的开发者控制台并查看错误来验证这一点。
要绕过这个问题,有几种方法。
你可以创建一个简单的Web服务器来运行你的代码。如果你有python,你可以直接运行命令(编辑:从你的包含index.html的文件夹)。
python -m SimpleHTTPServer
你可以在Chrome中禁用同源策略。https:/stackoverflow.coma60836771100379
使用Chrome浏览器的一个扩展程序,它可能会帮你做到这一点。我找了一个,这是第一个结果。Allow -Control -Allow -Origin(允许-控制-允许-起源)
一切都很好,只要确保你的语法是正确的.不要错过JSON中的逗号。
myApp.directive("hello", function() {
return {
restrict: 'E',
^
templateUrl:"hello.html"
};
})
实际上,我们需要为模板Url指令提供相对路径。相对路径完全取决于你提供路径的组件文件。
那么你的模板Url路径应该是这样的 - templateUrl:".hello.html"
打开chrome中的开发工具,进入网络选项卡,找到hello.html的reqest,将reqested路径与服务器上hello.html的路径进行比较。将hello.html移动到合适的位置或更新templeteUrl。
打开你的NodeJS命令提示符并安装 http-server 使用 npm install http-server
http-server 是一个简单的零配置命令行http服务器。
安装后,只需使用 http-server -o 在你的NodeJS命令提示符中。
下载Python并将其添加到你的路径环境变量中。
创建 启动python服务器的cmd文件 在index.html所在的目录下。
2 a) 在与index.html相同的根目录下创建一个新的文本文档。
2 b) write - python -m SimpleHTTPServer 8080。
2 c) 保存为 "所有文件 "类型,并使用一些名称,如startServer .cmd。
你可以在脚本中导入模板,并将其作为 "模板 "使用,而不是 "templateUrl"。
import hello from 'hello.html';
var myApp = angular.module('myApp', []);
myApp.directive("hello", function() {
return {
restrict: 'E'
template: hello
};
})
你可以使用。
userManagementApp.directive("ngCreateUserForm", function () {
return {
templateUrl : '/template/create.html'
};
});
而在服务器端,你必须把你的模板作为静态文件来提供
在围棋中。e.Static("/template", "/path/to/static/folder")
或者
在httpd配置中。
Alias /template/ "/path/to/template/folder"