Angular JS - 视图没有随html5Mode(true)而改变,但URL确实如此

时间:2018-03-25 23:36:05

标签: javascript angularjs html5 pretty-urls

我正试图摆脱#!来自URL。我有以下代码HTML和JS,

<head> 
    <base href="/"> 
</head>


<nav id="top-navigations" ng-app="portfolioApp">
            <a class="dropdown">Menu <span class="arrow">&#9660;</span></a>
            <ul ng-controller="sectionController">
              <li ng-repeat="navName in navNames"><a href="/about">{{navName.name}}</a></li>
            </ul>
</nav>


var portfolioApp=angular.module('portfolioApp',['ngRoute']);

portfolioApp.config(['$routeProvider', '$locationProvider', function($routeProvider,$locationProvider){

  $routeProvider
  .when('/about',{
    templateUrl:'views/about.html',
    controller:'sectionController'
  }).otherwise({
    redirectTo:'/'
  });

  $locationProvider.html5Mode(true);

}]);

地址栏中的网址更改为&#39; http://localhost:4000/about&#39;当我点击链接但视图没有呈现并保持不变。我有什么想法吗?

1 个答案:

答案 0 :(得分:1)

<强>首先

您必须创建两个州,例如homeabout

<强>第二

然后您必须创建一个可交换的视图<div ui-view="main"></div>

<强>第三

您必须正确使用网址,如下所示:

<a href="/about">About Me</a>
<a href="/home">Home</a> 

<强>第三 创建两个文件home.htmlabout.html。目录结构将是:

-index.html

-views / home.html的

-views / about.html

  

app.js

var app = angular.module("portfolioApp", ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
  var homeState = {
    name: 'home',
    url:'/home',
    views: {
        'main': {
          templateUrl: "views/home.html"
        }
      }
  }

  var aboutState = {
    name: '/about',
    url:'/about',
    views: {
        'main': {
          templateUrl: "views/about.html"
        }
      }
  }

  $stateProvider.state(homeState);
  $stateProvider.state(aboutState);
  $locationProvider.hashPrefix('');

  $urlRouterProvider.otherwise("/home");

});
  

的index.html

<html>
    <head>
         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
         <script src="app.js"></script>
         <style>.active { color: red; font-weight: bold; }</style>
         <base href="/">
    </head>
<body ng-app="portfolioApp">
<nav id="top-navigations">
            <a class="dropdown">Menu <span class="arrow">&#9660;</span>
                <a href="/about">About Me</a>
                <a href="/home">Home</a>
            </a>
</nav>
    <div ui-view="main"></div>
</body>
</html>
  

home.html的:

<p>Home</p>
  

about.html:

<p>About</p>