How do I pass a parameter not in the URL using Angularjs ui-router and components?

Issue

I cannot figure out how to pass a parameter using angularjs ui-router, since $stateParams has been depricated in ui-router 1.x. The ui-router documentation shows an example of passing a parameter through the URL, but no examples of passing a parameter that is not included as part of the URL.

{
  name: 'person',
  url: '/people/{personId}',
  component: 'person',
  resolve: {
    person: function(PeopleService, $transition$) {
      return PeopleService.getPerson($transition$.params().personId);
    }
  }
}

This used to be possible using $stateParams by adding a params object to the state object.

.state('contacts', {
        url: "/contacts",
        params: {
            param1: null
        },
        templateUrl: 'contacts.html'
    })

However, this requires the now deprecated $stateParams.

I have tried mixing the 2 methods, but I haven’t been able to get it to work.

{
  name: 'person',
  url: '/people/',
  component: 'person',
  params:{
    personId:null
  }
  resolve: {
    person: function(PeopleService, $transition$) {
      return PeopleService.getPerson($transition$.params().personId);
    }
  }
}

Has this ability been removed from ui-router? Is there a better way to pass parameters, especially objects, without making ridiculous URLs?

Solution

I have found that the parameters are passed through the $transition$ object. This object is not passed like a regular provider to the controller though. You pass the $transition$ object in through bindings on the component. $transition$ is automatically bound as is explained here.

ui-router Config:

.state({
        name: "contacts",
        url: "/contacts",
        params: {
            param1: null
        },
        component: "contacts"
    })

Controller:

module.component("contacts", {
    bindings: { 
        $transition$: '<'
    },
    controller: {
        var $ctrl = this;

        $ctrl.$onInit = function(){
            var param1 = $ctrl.$transition$.params().param1;
        };
    }
}

HTML Link

<a ui-sref="contacts({param1:$ctrl.myParam})" ui-sref-active="active">Contacts</a>

More information on using $transition$ and $transition$.params() can be found on ui-router’s Github page.

Answered By – Jdwill916

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.