我在项目中使用AngularJS设置路由,以便在单击菜单按钮时加载不同的模板。该模板基于浏览器URL。唯一的问题是,直接访问URL时不会加载模板。相反,它将加载一个空白页面(找不到对象)。如何克服这个?
因此该项目位于文件夹/ project4中的本地驱动器上。 有三个菜单按钮,其中两个链接到:
project4/about
和project4/contact
这是HTML部分:
<html>
<head>
<base href="/ordina/angular/project4/">
<link href=
"//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel=
"stylesheet">
<link href=
"//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel=
"stylesheet">
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="script.js"></script>
<title></title>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Angular Routing
Example</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li>
<a href=""><i class="fa fa-home"></i> Home</a>
</li>
<li>
<a href="about"><i class="fa fa-shield"></i> About</a>
</li>
<li>
<a href="contact"><i class="fa fa-comment"></i>
Contact</a>
</li>
</ul>
</div>
</nav>
</header>
<div id="main">
<div>
<p>This text is not being shown in the frontend.</p>
</div>
</div>
</body>
</html>
这是.js文件:
// script.js
// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function ($logProvider, $routeProvider, $locationProvider) {
$logProvider.debugEnabled(true);
$locationProvider.html5Mode(true);
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController',
controllerAs: 'home'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController',
controllerAs: 'about'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController',
controllerAs: 'contact'
});
//$locationProvider.hashPrefix('!');
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
答案 0 :(得分:4)
您已启用html5mode。为了使URL工作的GET请求,您必须首先实现URL重写到AngularJS应用程序的入口点。 (这是在.htaccess中完成的服务器端)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) /index.html [NC,L]
修改强> XAMPP中的htaccess
rename c:\pathtoyourhtaccessfile\htaccess.txt .htaccess
AllowOverride All
必须设置为&#34;全部&#34;,不是&#34;无&#34;或者......其他的