0
votes

Question: For some reason I can't get my controller to recognize my url parameters across sessions.

Background: I have a nested view called modal that takes a parameter, whose url is /modal/:id (eg: /#/modal/1/ or /#/floorplan/1+2/). Ideally, when the user goes to this url, a modal will automatically open with the resource(s) with the given id.

Since the parent state and the child state(modal) are being handled by the same controller, the modal state has a custom data attribute (modalStatus) in its configuration set to true. When this custom attribute is enabled the modal is displayed.

I can currently go from the parent state to the nested state and trigger the modal but when I start a new session or refresh the page with a url like /modal/3, the application fails to read the parameters ($stateParams), which is being logged as an empty object.

I have tried using onEnter and Resolve but I'm not exactly clear on how to use them in this scenario.

Router

$stateProvider
  .state('home', {
    name: 'home',
    url: '/',
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  })
  .state('home.modal', {
    url: 'modal/:id/',
    data: {
      modalState: true
    },
    controller: 'MainCtrl'
  })

Relevant part of controller:

$scope.init = function() {
  console.log($stateParams);
  if ($state.current.data) {
    if ($state.current.data.modalState === true) {
      $scope.openModal();
    }
  }
};

$scope.init();

edit: plunkr

1
your code seems to be ok and $stateParams should log the object when you are in child state..could you please show the fiddle with your problem.. - Asik
your plunker is showing errors. - Callum Linington
Yup sorry about that. Just fixed them - alexdmejias

1 Answers

0
votes

You could try adding the params option:

$stateProvider
  .state('home', {
    name: 'home',
    params: {
      id: null
    },
    url: '/',
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  })
  .state('home.modal', {
    url: 'modal/:id/',
    data: {
      modalState: true
    },
    controller: 'MainCtrl'
  });

The child state home.modal should inherit the params of the parent. On your ui-sref from one state to another, pass the param like so:

<a ui-sref="home.modal({ id: x })"></a>

Then your url would turn out to be /modal/:x (where x is the number).

Also the $stateParams should then show the params as you wished.