AngularJS:指令不使用templateUrl

时间:2014-07-09 17:36:47

标签: angularjs

角度新手,我在过去一小时左右应该是一个简单的指令时遇到了麻烦。真的很感激一些帮助!

我相信你好,应该出现,似乎无法让它发挥作用?

的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>

main.js

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

hello.html的

<p>Hello</p>

8 个答案:

答案 0 :(得分:13)

如果您正在本地测试并使用谷歌浏览器,那么这将无效,因为AngularJS正在对这些html文件进行Ajax调用,但Chrome会阻止此错误:

  

XMLHttpRequest无法加载file:/// [filepath ...]交叉原点   请求仅支持协议方案:http,data,chrome,   chrome-extension,https,chrome-extension-resource。

您可以通过打开开发人员控制台并查看错误来验证这一点。

要解决这个问题:

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

    python -m SimpleHTTPServer

  2. 您可以在Chrome中停用相同的来源政策: https://stackoverflow.com/a/6083677/1100379

  3. 使用可能会为您执行此操作的Chrome扩展程序。我看了一眼,这是第一个结果: Allow-Control-Allow-Origin

答案 1 :(得分:9)

一切正常,只需确保您的语法正确。 不要错过JSON中的逗号

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

演示:http://plnkr.co/edit/Z6rjbsuqzmcD4gBem36c

答案 2 :(得分:1)

实际上我们需要给出templateUrl指令的相对路径。相对路径完全取决于您给出路径的组件文件。

假设您的文件路径可能类似于 - app / hello.html

然后你的templateUrl路径应该像 - templateUrl:&#34; ./ hello.html&#34;

答案 3 :(得分:0)

在chrome中打开dev工具转到网络选项卡找到hello.html reqest请求路径与您在服务器上的hello.html路径。将hello.html移到适当的位置或更新templateUrl

答案 4 :(得分:0)

打开您的NodeJS命令提示并使用 npm install http-server

安装 http-server

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

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

答案 5 :(得分:0)

  1. 下载Python并将其添加到路径环境变量

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

  3.   

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

         

    2 b)写 - python -m SimpleHTTPServer 8080

         

    2 c)保存为“所有文件”类型,并使用某些名称,如startServer .cmd

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

答案 6 :(得分:0)

您可以在脚本中导入模板,并将其用作“模板”,而不是“ templateUrl”:

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

答案 7 :(得分:0)

您可以使用:

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

在服务器端,您必须像静态文件一样提供模板

在执行中:e.Static("/template", "/path/to/static/folder")

在httpd配置中:

Alias /template/ "/path/to/template/folder"