[英]Why AngularJS routes are not working in local?
我有如下實現 AngularJS 路由的 html 文件,
索引.html:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ng-view>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.1/angular-route.min.js"></script>
<script>
// Code goes here
var demo = angular.module('demo', ['ngRoute']);
demo.config(function($routeProvider){
$routeProvider.when('/', {
controller: 'testController',
templateUrl: 'test.html'
})
})
var controllers = {};
controllers.testController = function($scope){
$scope.first = "Info";
$scope.customers=[
{name:'jerry',city:'chicago'},
{name:'tom',city:'houston'},
{name:'enslo',city:'taipei'}
];
}
demo.controller(controllers)
</script>
</body>
</html>
測試.html:
<div>
<input type="text" ng-model="name"/>
</br>
{{first}}
</br>
<ul>
<li ng-repeat="cust in customers | filter:name">{{cust.name | uppercase}} - {{cust.city}}</li>
</ul>
</div>
你可以在這里找到工作版本
但是為什么當我在本地瀏覽器中運行它時它不起作用:(
這是 chrome 控制台錯誤:
任何幫助表示贊賞! :)
說清楚很重要。 出於安全原因,Chrome(例如)不允許您加載本地文件(即:視圖的模板)。 我的建議是設置一個 Web 服務器來測試您的應用程序:
或者,您可以使用內聯模板代替外部加載,但這似乎不是一個好習慣。
編輯:
使用您發布的控制台錯誤打印,Chrome 阻止了您的 ajax 請求。 您可以使用命令行參數繞過此限制:
chrome.exe --allow-file-access-from-files
但是,我鼓勵您設置一個簡單的本地 Web 服務器,它可以防止您在學習時遇到一些麻煩...
您可以使用 Firefox 進行測試。 路由和 ajax 將起作用。 但是最好設置一個像@gustavodidomenico 所說的網絡服務器
使 ng-view 在本地工作的解決方法是將其他 html 的內容放在腳本標記中
<script type="text/ng-template" id="index22.html">
This is index 2 template.
</script>
<script type="text/ng-template" id="index33.html">
This is index 3 template.
</script>
在進行調用的同一 HTML 中。
ngview 進行 AJAX 調用以加載外部 HTML 或單獨 HTML 的內容,chrome 不允許對本地資源進行 AJAX 調用,IE 11 還顯示“訪問被拒絕”錯誤消息。
當包含在腳本標簽中時,不會進行此 AJAX 調用。
有一個名為Web Server for Chrome的Chrome Extension
。 你可以添加它然后午餐它,在瀏覽對話框中選擇你的工作文件夾,然后它給你一個Local URL
,你可以在那里測試你的應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.