簡體   English   中英

無法使用AngularJS進行路由

[英]Cannot get routing to work with 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: '/' });
});

它應該是,

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

DEMO

我認為你應該注入$ locationProvider,因為你正在使用它,但我沒有看到注入。

你可以嘗試將$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('!');
}]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM