Angular的路由和参数不起作用

Angular routes and parameters don't work

本文关键字:参数 不起作用 路由 Angular      更新时间:2023-09-26

我有以下控制器:

app.controller('ObjectBoardCtrl', ['$scope' , '$rootScope' , '$routeParams' , 
  function($scope , $rootScope, $routeParams) {
    $scope.selectedObjectId = $routeParams.id;
}]);

和这个路由配置:

app.config(['$routeProvider',
  function($routeProvider, $routeParams) {
    $routeProvider.when('/object/:id', {
        controller: 'ObjectBoardCtrl'
      });
  }]);

无论我做什么,$routeParams对象都是空的。我试图使用#/object/4334访问不同的页面,并在我的页面上链接到不同的id,但它拒绝更新$routeParams对象。不用说,ngRoute被注入了,并且控制台上没有错误。我遗漏了什么?(我几乎遵循了我找到的每一个教程)。

谢谢!

试着从你的配置函数中删除$routeParams,你不需要他们在那里。使用空模板,所以你的路由看起来像这样:

app.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/object/:id', { controller: 'ObjectBoardCtrl', template: '' }); }]);

在你的html文件中使用<div ng-view></div>作为控制器的容器

试一试:

$scope.selectedObjectId = $route.current.params.id;

注入$route