2017-05-19 242 views
0

我想在角js做路由和服務器運行良好。但角度路由不能正常工作,只有main.html頁面進入ng-view,second.html不會來。當點擊第一個和第二個HTML相同的mainController工作不是第二個控制器。角度路由不能正常工作?

HTML

<!Doctype html> 

<html ng-app="myApp"> 
<meta charset=utf-8" /> 
<head> 


<script src="http://code.angularjs.org/snapshot/angular.min.js"></script> 
<script src="http://code.angularjs.org/snapshot/angular-route.min.js"> 
</script> 
<script type="text/javascript"src="app.js"></script> 
<body> 
<header> 
    <li><a href="#/"><i></i>first</a></li> 
    <li><a href="#/second"><i></i>Second</a></li> 
</header> 

    <div class = "container"> 



    <div ng-view> 

       </div> 

     </body>  

main.html中

<h1> this is main </h1> 

second.html

<h1> this is second </h1> 

app.js

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

myApp.config(function ($routeProvider){ 

$routeProvider 

.when('/',{ 
    templateUrl: 'pages/main.html', 
    controller: 'mainController', 
}) 

.when('/second',{ 
    templateUrl: 'pages/second.html', 
    controller: 'secondController', 
}) 

    }); 

    myApp.controller('mainController', 
     ['$scope','$log','$location',function($scope,$log,$location){ 

     $log.info($location.path()); 
     console.log("first"); 

    }]); 

    myApp.controller('secondController', 
     ['$scope','$log','$location',function($scope,$log,$location){ 

     $log.info($location.path()); 
     console.log("second"); 

    }]); 
+0

你在控制檯遇到錯誤? – Zooly

+0

「secondController」在哪裏? –

回答

0

問題是您的scripts,他們不工作使用從googleapis

var myApp = angular.module('myApp', ['ngRoute']); 
 
myApp.config(function ($routeProvider) { 
 
    $routeProvider 
 
     .when('/', { 
 
      template: '<h1>Main Page</h1>', 
 
      controller: 'mainController', 
 
     }) 
 
     .when('/second', { 
 
      template: '<h1>{{ test }}</h1>', 
 
      controller: 'secondController', 
 
     }) 
 
}); 
 
myApp.controller('mainController', 
 
    ['$scope', '$log', '$location', function ($scope, $log, $location) { 
 
     $log.info($location.path()); 
 
     console.log("first"); 
 
    }]) 
 
    .controller('secondController', ['$scope', function ($scope) { 
 
     $scope.test = 'Testing angular routes'; 
 
    }]);
<script src="https://code.angularjs.org/1.6.4/angular.js"></script> 
 
<script src="https://code.angularjs.org/1.6.4/angular-route.min.js"></script> 
 
<body ng-app="myApp"> 
 
<header> 
 
    <li><a href="#!/"><i></i>first</a></li> 
 
    <li><a href="#!/second"><i></i>Second</a></li> 
 
</header> 
 
<div class="container"> 
 
    <div ng-view> 
 
    </div> 
 
</div> 
 
</body>

+0

非常感謝.. !! – anant

+0

爲什麼這不與腳本運行 \t anant

+0

不要將其更改爲模板....不能使用templateUrl運行 (希望包含更大的html文件) – anant