无法通过 Angularjs 中的templateUrl加载模版。

71 浏览
0 Comments

无法通过 Angularjs 中的templateUrl加载模版。

我正学习Angularjs,学习如何使用templateUrl来加载模板。

我有一个简单的指令:

var mainApp = angular.module("mainApp", []);
mainApp.directive("request", function() {
    return {
        restrict: "E",
        scope: {
            data: "@"
        },
        templateUrl: "te.html"
    }
})

我尝试像这样使用这个指令:


    
        
        

 

    
                    title
                    actions
                        
    

一旦打开页面,我就遇到了这个异常:

XMLHttpRequest cannot load file:///Users/chenguangli/Documents/workspace-web/ournotes/te.html. Origin null is not allowed by Access-Control-Allow-Origin.   default.html:0
Error: Failed to load template: te.html
    at Error ()
    at file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:4503:17
    at file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:8898:11
    at wrappedErrback (file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:6806:57)
    at file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:6882:53
    at Object.Scope.$eval (file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:8011:28)
    at Object.Scope.$digest (file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:7876:25)
    at Object.Scope.$apply (file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:8097:24)
    at done (file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:9111:20)
    at completeRequest (file:///Users/chenguangli/Documents/workspace-web/ournotes/js/angular.js:9274:7)    js/angular.js:5704
    js/angular.js:5704
    js/angular.js:4800
  wrappedErrback    js/angular.js:6808
    js/angular.js:6882
  Scope.$eval   js/angular.js:8011
  Scope.$digest js/angular.js:7876
  Scope.$apply  js/angular.js:8097
  done  js/angular.js:9111
  completeRequest   js/angular.js:9274
  xhr.onreadystatechange    js/angular.js:9244

我肯定没有尝试跨域加载模板文件(te.html与default.html在同一个文件夹中)。

是否有人能帮我弄清楚其中的问题?

admin 更改状态以发布 2023年5月22日
0
0 Comments

如果您已经安装了Node和NPM,请运行:npm install http-server -g,然后转到包含您的应用程序的文件夹并运行:http-server。我在这个SO帖子中找到了答案:Quick Node Server。您可以在此处下载Node(NPM随Node一起提供):Node。希望这可以帮助您!

0
0 Comments

问题在于您正在使用文件系统(使用“file://”协议)运行示例,而许多浏览器(Chrome,Opera)在使用“file://”协议时会限制XHR调用。 AngularJS模板是通过XHR下载的,这与使用“file://”协议相结合,导致了您所遇到的错误。\n\n在解决这种情况时,有几个选项可供选择:\n\n- 使用Web服务器(有许多易于解决的解决方案,如https://code.google.com/p/mongoose/ 或几行Node.js脚本)运行您的示例。\n- 使用