最近用到Angular路由,无刷新的单页切换模式令人眼前一亮,但我是有强迫症的,那个"#"号实在是太刺眼了,太影响美观了!
1 var mainApp = angular.module("ViewsApp", ['ngRoute']). 2 config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) { 3 $routeProvider.when("/login", { 4 templateUrl: "/Route/Views/Login.html", 5 controller: function ($scope, $location) { 6 $scope.User = { 7 UserName: "", 8 PassWord:"" 9 } 10 $scope.Login = function () { 11 if ($scope.LoginForm.$valid) { 12 $location.search({ name: 'Ari', username: 'auser' }); 13 $location.path("/index").replace();//如果你希望跳转后用户不能点击后退按钮(对于登录之后的跳转这种发生在某个跳转之的 14 // 再次跳转很有用),AngularJS提供了replace()方法来实现这个功能: 15 } 16 17 } 18 } 19 }).when("/", { 20 template: "<h1>内容部分</h1>", 21 // redirectTo:"/index" 22 redirectTo: function (route,path,search) { 23 return "/index"; 24 } 25 26 }).when("/detail/:id&:name", { 27 templateUrl: "/Route/Views/Detail.html", 28 controller: "DetailController", 29 reloadOnSearch: true, 30 }).otherwise({ 31 template: "<h2>这个是默认的模板哦</h2>", 32 controller: function ($scope) { 33 }, 34 35 }); 36 }])
不过Angular团队提供了解决方案,那就是Hmtl5Mode。使用起来也就是寥寥两步:
1.在配置中:
angular.module('myApp', ['ngRoute'])
.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
}]);
2.在HTML文档的HEAD中用标签来指定应用的基础URL:
<base href="/" />
现在看起是这样的了,"#"已经被完美的干掉了。
不要高兴的太早,当按下f5后变成这样了:
什么鬼?不过仔细一想.net的运行机制就明白了,请求要先走服务端的,服务端解析根本就没有这个页面,肯定报404错误了!那重写url不就得了
我是这么做的,在web.config 中加入如下代码:
<system.webServer>
<!--angular重写url-->
<rewrite>
<rules>
<rule name="angularjs routes"
stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}"
matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}"
matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}"
pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/Route/Demo.html" />
</rule>
</rules>
</rewrite>
<!--angular重写url-->
</system.webServer>
再F5刷新就正常了!^^