10

我正在尝试运行此代码:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>Exemple 06</title>
</head>
<body>
    <!-- Diretiva ng-repeat -->
    <div ng-controller="MyController">
        <a ng-href="#/">Page 1</a> | <a ng-href="#/p2">Page 2</a>
        <div ng-view="#/p2"></div>
    </div>

    <script src="js/angular.js"></script>
    <script src="js/angular-route.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', ['ngRoute']);

        myApp.config(function($routeProvider){
            $routeProvider
                .when('/'  , {controller: 'MyController', templateUrl: 'p1.html'})
                .when('/p2', {controller: 'MyController', templateUrl: 'p2.html'})
                .otherwise({ redirectTo: '/'});
        });

        myApp.controller('MyController', function($scope){
            $scope.nomes = [
                {id: 1, nome: 'Arthur'},
                {id: 2, nome: 'Portos'},
                {id: 3, nome: 'Aramis'}
            ];
        });
    </script>
</body>

但出现以下错误:

XMLHttpRequest 无法加载文件:///home/93579551515/Desktop/Angular/p1.html。仅 HTTP 支持跨源请求。

我不想在网络服务器上运行它。

4

3 回答 3

30

如文档中所述,您可以通过将模板放在标签中来添加模板,例如p1.html和。p2.htmlindex.htmlscript

<script type="text/ng-template" id="p1.html">
  This is the content of the template
</script>

然后angular将不再需要发出 AJAX 请求来获取它们。

请注意,这些script元素必须出现 ng-app.

于 2013-11-07T22:03:42.597 回答
1

我在 Chrome 中遇到了同样的问题,如果您使用的是 Chrome,您可以在 Chrome 中禁用同源策略。启动 Chrome 运行:

$ google-chrome --disable-web-security

这里有更多细节

于 2014-08-31T07:10:38.193 回答
0

Route provider uses http protocol that's why if you will run this code directly from folder, you will get cross origin issue.

Keep your folder on a server like localhost/route and run it.

Provide reference path like templateUrl: '/p1.html'

于 2017-07-10T05:34:06.593 回答