2017-02-16 50 views
0

有人想法,爲什麼:message always throws「undefined」?我所說的頁面 「MyDomain.com/#AMessage」angularjs routing:param always undefined

ctrl.js:

angular.module('AutApp', ['ngRoute']) 

.config(function($routeProvider){ 
    $routeProvider.when("/:message", 
    { 
     templateUrl: "index.html", 
     controller: "ctrl" 
    } 
); 
}) 

.controller('ctrl', function($routeParams) { 
    document.getElementById("test").innerHTML = $routeParams.message; 
}); 

的index.html:

<!DOCTYPE html> 
<head></head> 
<body ng-app="AutApp" ng-controller="ctrl"> 
    <div id = "test"></div> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script> 
    <script src="ctrl.js"></script> 
</body> 
</html> 

謝謝您的幫助!

回答

1

您沒有正確使用ng-route。你必須定義一個視圖。該視圖的模板不能是index.html,因爲該頁面是應用程序的根。您的控制器應與路線相關聯。 More info on ng-route

<!DOCTYPE html> 
<body ng-app="AutApp"> 
    <div ng-view></div> 

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script> 
    <script> 

    angular.module('AutApp', ['ngRoute']) 

    .config(function($routeProvider){ 
     $routeProvider.when("/:message", 
    { 
     template: '<div id = "test"></div>', 
     controller: "ctrl" 
    } 
); 
}) 

.controller('ctrl', function($routeParams) { 
    document.getElementById("test").innerHTML = $routeParams.message; 
}); 

</script> 

+0

非常感謝您! – Irondonut