无法使用AngularJS进行路由

时间:2017-06-13 16:27:25

标签: javascript jquery html angularjs web

我正在创建一个网络组合,主页面上有一个菜单。当用户点击“视频”时我希望该网站访问mywebsite.com/video并转到video.html。我使用的是AngularJS,但我无法弄清楚我做错了什么。

的index.html

<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body ng-app="myApp">
<nav class="topnav" id="myTopnav">
    <a href="#portfolio">Portfolio</a>
    <a href="#events">Upcoming Events</a>
    <a href="#cv">CV</a>
    <a href="#video">Video Reel</a>
</nav>
<div class="ng-view"></div>
</body>

main.js

var app = angular.module('myApp', ["ngRoute"]);

app.config(function($routeProvider) {

$routeProvider
    .when(
    '/', {
        redirectTo: '/home'
    })
    .when('/portfolio', {
        templateUrl: 'templates/portfolio.html'
    })
    .when('/events', {
        templateUrl: 'templates/events.html'
    })
    .when('/cv', {
        templateUrl: 'templates/cv.html'
    })
    .when('/video', {
        templateUrl: 'templates/video.html'
    })
    .otherwise({ redirectTo: '/' });
});

3 个答案:

答案 0 :(得分:1)

应该是,

 <a href="#/portfolio">Portfolio</a>
 <a href="#/events">Upcoming Events</a>
 <a href="#/cv">CV</a>
 <a href="#/video">Video Reel</a>

<强> DEMO

答案 1 :(得分:1)

我认为你应该注入$ locationProvider,因为你正在使用它,但我看不到注射。

答案 2 :(得分:1)

您可以尝试将$locationProvider服务添加到配置中并更改href属性

//html
<body ng-app="myApp">
<nav class="topnav" id="myTopnav">
    <a href="#/portfolio">Portfolio</a>
    <a href="#/events">Upcoming Events</a>
    <a href="#/cv">CV</a>
    <a href="#/video">Video Reel</a>
</nav>
<div class="ng-view"></div>
</body>

//js
app.config(['$routeProvider','$locationProvider',
  function($routeProvider,$locationProvider) {

$routeProvider
    .when(
    '/', {
        redirectTo: '/'
    })
    .when('/portfolio', {
        templateUrl: 'templates/portfolio.html'
    })
    .when('/events', {
        templateUrl: 'templates/events.html'
    })
    .when('/cv', {
        templateUrl: 'templates/cv.html'
    })
    .when('/video', {
        templateUrl: 'templates/video.html'
    })
    // removed other routes ... *snip
    .otherwise({
        redirectTo: '/'
    }
);

// enable html5Mode for pushstate ('#'-less URLs)
//$locationProvider.html5Mode(true);
//$locationProvider.hashPrefix('!');
}]);