2016-12-16 59 views
0

我的文件夾結構是:AngularJs 1個路由不工作

-ngTest 
    --Scripts(all js files) 
    --index.html 
    --main.js 
    --partialView.html 

index.html的代碼如下:

<!DOCTYPE html> 
<html ng-app="myApp"> 
    <head> 
     <title>Angular App</title> 
     <meta charset="utf-8" /> 
    </head> 
    <body> 
     <p>Hello world</p> 
     <div ng-view></div> 
     <script src="Scripts/angular.js"></script> 
     <script src="Scripts/angular-route.js"></script> 
     <script src="main.js"></script> 
    </body> 
</html> 

main.js是:

angular.module('myApp', ['ngRoute']).config(function ($routeProvider) { 
    $routeProvider.when('/home', { 
     templateUrl: 'partialView.html', 
     controller: 'newCtrl' 
    }) 
}).controller('newCtrl', function() { 
    console.log('finally'); 
}); 

partialView.html :

<div> 
    <p> From view</p> 
</div> 

我是什麼在此代碼缺少什麼?

+0

也許你缺少的默認路由: 。否則({redirectTo: '/家'}) –

回答

0

如果要加載partialView.html爲默認,你必須到達「/」,而不是「/家」。

angular.module('myApp', ['ngRoute']).config(function ($routeProvider) { 
    $routeProvider.when('/', { 
     templateUrl: 'partialView.html', 
     controller: 'newCtrl' 
    }) 
}).controller('newCtrl', function() { 
    console.log('finally'); 
}); 

「/ HTML」,如果你在你的HTML文件鏈接到它,例如與將要被訪問:

<a href=#/html>Link<a> 
0

您的代碼看起來不錯,但缺少的東西: 你需要一個錨,使你去到/ home,您可以在索引文件中添加它如下:

<a href="#/home">Red</a> 

然後單擊主錨,讓您的局部視圖出現。 或者
在路由器的配置修改主頁,使其只有「/」,這樣的代碼將如下所示:

angular.module('myApp', ['ngRoute']).config(function ($routeProvider) { 
$routeProvider.when('/', { 
    templateUrl: 'partialView.html', 
    controller: 'newCtrl' 
}).controller('newCtrl', function() { 
console.log('finally');}); 

最後一件事,如果你採用了棱角分明的最新1.6.0,你必須添加以下代碼:

appModule.config(['$locationProvider', function($locationProvider) { 
    $locationProvider.hashPrefix('');}]);