带参数问题的角度路由

时间:2015-10-29 08:27:02

标签: angularjs angularjs-routing

我有MVC应用程序,我想为以下URL进行路由

http://localhost:2668/Home/User/1

我试试

.config(function ($routeProvider, $locationProvider) {
//here we will write code for implement routing 
$routeProvider
.when('#/Home/User/:userid', {
    templateUrl: '/AngularTemplates/User.html',
    controller: 'UserController'
})

.otherwise({   // This is when any route not matched
    controller: 'ErrorController'
}) })

然后UserController如下:

.controller('UserController', ['$scope','$routeParams', function ($scope,$routeParams) {
    // $routeParams used for get query string value

    //var loc = window.location.href;
    //var id = loc.slice(loc.lastIndexOf('/'), loc.length).split('/')[1];
    $scope.Message = "This is ORDER Page with query string id value =" + $routeParams.userid;
}])

但我总是得到"未定义"对于段$routeParams.userid

我的代码有什么问题?请帮助谢谢!

1 个答案:

答案 0 :(得分:1)

这是一个有效的例子:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>

    <a href="/Home/User/11">user 11</a>
    <a href="/Home/User/12">user 12</a>

    <div ng-view></div>

    <script>
      var app = angular.module('app', ['ngRoute']);

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

              $locationProvider.html5Mode({
                  enabled: true,
                  requireBase: false
              }).hashPrefix('!');

              $routeProvider
                .when('/Home/User/:userid', {
                    template: '<pre>{{ message }}</pre>',
                    controller: 'UserController'
              });
          }]);

      app.controller('UserController', ['$scope','$routeParams', function ($scope, $routeParams) {
          $scope.message = "userid = " + $routeParams.userid;
      }]);
    </script>
  </body>

</html>

JSBin http://output.jsbin.com/geluli

您可以在此处阅读有关默认路由器的更多信息(很好的示例+测试)https://docs.angularjs.org/api/ngRoute/service/$route