3

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot :). With that $watch I can track url changes, works perfectly. But I have another problem, when the page loads for the first time, $routeParams is undefined when my controller is being loaded, i can reference it in the html and it works but not in the controller. Thanks again for your help.
@PedroGarcía Why do you need to reference it? Can you create an updated example from my demo where it doesn't work?
I couldn't find how to change the default url in plunker. However i added some comments in the js file explaining where is the problem . plnkr.co/edit/raDtomFubQ56w6oiBvZT?p=preview
@PedroGarcía You should do all work (e.g. loading the content) inside the $watch. Only the $watcher will be executed over and over again as the $routeParams.id changes, the rest of the controller will not be. Also, the first time around, the $routeParams.id may not be set because the order of execution of the controller and the router is not determined. Alternatively, you could use one route in the $routeProvider with your whole app's template rendered in ng-view. This will load the controller (and the template) over and over as the route changes, including the first time.
That clarifies it a lot! I am going for the last option and follow the angular way. Thanks :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.