angularjs routing:param总是未定义的

时间:2017-02-16 20:30:31

标签: angularjs routing

有人有一个想法,为什么:消息总是抛出"未定义"?我用" MyDomain.com/#AMessage"

调用该页面

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 个答案:

答案 0 :(得分: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>