【问题标题】:AngularJS routing doesn't work with templateUrl?AngularJS 路由不适用于 templateUrl?
【发布时间】:2017-01-06 16:21:24
【问题描述】:

我非常努力地完成这项工作,但我所有的尝试都失败了。我正在尝试学习 Angular 路由,我开始非常简单:在同一个文件夹中创建了 4 个文件:index.html、page1.html、page2.html 和 page3.html。 这是 index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>routing</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<script src="D:\Developer Library\MyAngular\angular.min.js"></script>
<script src="D:\Developer Library\MyAngular\Scripts\angular-route.js"></script>

<body ng-app="myApp">
    <a href="#page1">one</a>
    <a href="#page2">two</a>
    <a href="#page3">three</a>
    <div ng-view></div>
    <script>
                var app = angular.module('myApp', ['ngRoute']);
                app.config(function ($routeProvider) {
                    $routeProvider
                        .when('/page1', { templateUrl: 'D:\Developer Library\dom\AngularRouting\page1.html' }).
                        when('/page2', { template: '<h1>page2.html</h1>' })//the template is working fine unlike templateUrl
                        .when('/page3', { template: '<h1>page3.html</h1>' });
                    //page1.html, page2.html, page3.html are just files holding headers with some text.-->
                })
            </script>
</body>

</html>

我在控制台窗口中遇到了这些错误:

XMLHttpRequest 无法加载 file:///D:/Developer%20LibrarydomAngularRoutingpage1.html。叉 源请求仅支持协议方案:http、data、 chrome, chrome-extension, https, chrome-extension-resource.

和:

错误:[$compile:tpload] http://errors.angularjs.org/1.5.8/$compile/tpload?p0=D%3ADeveloper%20LibrarydomAngularRoutingpage1.html&p1=-1&p2= 在 angular.min.js:6 在 angular.min.js:156 在 angular.min.js:131 在 m.$eval (angular.min.js:145) 在 m.$digest (angular.min.js:142) 在 m.$apply (angular.min.js:146) 在 HTMLBodyElement。 (角度.min.js:115) 在旧金山(angular.min.js:37) 在 HTMLBodyElement.d (angular.min.js:37)

我进行了所有可能的更改以使其正常工作:我将锚元素的 href 值更改为 /#/page1#/page1/pagepage,我还将 templateUrl 值更改为类似的值(我最后一次尝试是文件的完整路径!) 我实际上对href 值和when 方法的第一个参数以及templateUrl 感到困惑,所以我有一些问题我认为可以帮助我理解路由在角度中的工作原理:

它们各自指的是:hrefwhen 方法的第一个参数是否相同? 我可以为href 属性分配任何值,并在when 参数中引用它吗?

templareUrl的值与当前文件(index.html)的位置有关,

井号 # 是什么意思,为什么它很重要?

【问题讨论】:

  • 请提供您托管应用程序的路径,而不是 D:\... 可能是 \Scripts\angular-route.js\Scripts\angular.min.js

标签: angularjs


【解决方案1】:

Angular 正在通过 AJAX 加载模板,AJAX 无法访问本地文件系统。

您必须在服务器上运行您的应用程序(您可以使用本地服务器)才能使 templateUrl 工作。

【讨论】:

  • 谢谢。您能否解释一下锚中的哈希符号和配置函数中的正斜杠之间的约定,或者如果可能的话给出一个解释它的链接?
  • 哈希符号是 Angular 如何在不重新加载页面的情况下检测 URL 中的更改(哈希最初用于页内书签),因此 Angular 利用此机制来检测 URL 中的更改不会导致页面重新加载,但会触发角度路由。 Angular 还支持 HTML5 模式(使用历史 API)。在 Angular $location 文档(Hashbang 和 HTML5 模式)中了解此内容:docs.angularjs.org/guide/$location
猜你喜欢
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2018-01-07
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
相关资源
最近更新 更多