我在AngularJS中有一个简单的单页面应用程序。该网址显示为.../Angular/index.html
,当我点击页面中的链接时,它会转换为.../Angular/index.html#/addStudent
。
现在,我想从网址中删除#
,但我无法执行此操作。我用Google搜索并找到了许多答案,但没有一个有用(我对Angular和编程很新),所以可能是我错过了一些非常愚蠢的东西。
以下是代码:
<html>
<head>
<title>Angular JS Views</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp">
<p><a href = "#addStudent">Add Student</a></p>
<p><a href = "#viewStudents">View Students</a></p>
<div ng-view></div>
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
<script type = "text/ng-template" id = "viewStudents.htm">
<h2> View Students </h2>
{{message}}
</script>
</div>
<script>
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addStudent', {
//url:'/',
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
//url:'/',
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
//$urlRouterProvider.otherwise('/');
//$locationProvider.html5Mode(true);
//check browser support
// if(window.history && window.history.pushState){
//$locationProvider.html5Mode(true); will cause an error $location in HTML5 mode requires a tag to be present! Unless you set baseUrl tag after head tag like so: <head> <base href="/">
// to know more about setting base URL visit: https://docs.angularjs.org/error/$location/nobase
// if you don't wish to set base URL then use this
// $locationProvider.html5Mode({
// enabled: true,
// requireBase: false
// rewriteLinks: true
// });
// }
}]);
mainApp.controller('AddStudentController', function($scope) {
$scope.message = "This page will be used to display add student form";
});
mainApp.controller('ViewStudentsController', function($scope) {
$scope.message = "This page will be used to display all the students";
});
</script>
</body>
</html>
答案 0 :(得分:0)
您需要将HTML5模式设置为true:
$locationProvider.html5Mode(true);
在您的链接中,请勿包含#
。这样做是这样的:
<a href="/addStudent">Add Student</a>
答案 1 :(得分:0)
使用
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
在您的js和
中<base href="http://localhost:4000" || "or your URL in here">
主HTML中的
不要忘记配置中的$locationProvider
。
答案 2 :(得分:0)
如果要删除前缀(#
),可以执行以下操作:
$locationProvider.html5Mode(true);
/
&gt;中的<head
在index.html上<head>
...
<base href="/">
</head>
请注意,如果您使用的是Angular 1.6,则还需要删除!
。您可以看到this solution。