Angular route when() without mapping to controller

2019-07-01 11:58发布

问题:

It's possible to use when() without mapping to any controller or template?

This is how I have configured my routes:

app.config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/presentations/:id', {});
});

I need to use routeParams in my controller:

app.controller('PresentationController', function($scope, $routeParams) {
    console.log($routeParams);
});

This doesn't work. I don't need ngView but I added it in case is needed. My controller is already loaded with the ng-controller directive.

回答1:

One has to continuously watch the $routeParams.id for changes in this case: http://plnkr.co/edit/x2cPxVWPqVePDule1aOk?p=preview

$scope.$watch(function () { return $routeParams.id; }, function (newVal) {
  if (typeof newVal === 'undefined') return;
  $scope.id = newVal;
})

Also, having an ng-view in the template is necessary.