Blake Niemyjski
Blake Niemyjski

Reputation: 3577

Angular UI-Router Resolve Optional Parameter

I have the following route:

    $stateProvider.state('project.dashboard', {
        url: '/:id/dashboard',
        controller: 'Dashboard',
        controllerAs: 'vm',
        templateUrl: 'project/dashboard.tpl.html'
    });

I'd like to have id be an optional parameter that gets resolved via a service if it's not defined.

so /project/dashboard also resolves to /project/ID/dashboard

What would the best way to accomplish this as I came up short looking at all the docs and google. Also if anyone has any tips for exposing the the current selected id via a service sitewide so my ui-sref's work that would be great :)

Note I was able to get this to somewhat work via this (but it really sucks and I don't like it)

    $urlRouterProvider.when('/project/dashboard', function() {
        // TODO: Resolve current project id from service.
        return '/project/MY_PROJECT_ID/dashboard';
    });

Upvotes: 3

Views: 2045

Answers (1)

Chris T
Chris T

Reputation: 8216

You want to use a Default Parameter Value.

See this Plunk: http://plnkr.co/edit/IAr878eKQ4fTUKvAUoZD?p=preview

app.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("/user");
  $stateProvider.state({ 
    name: 'user', 
    url: '/user/:userId', // userId param
    controller: function($scope, $stateParams) { 
      // based on param, pull user from rootscope (this should probably be a resolve in real life)
      $scope.user = $scope.users[$stateParams.userId]
    }, 
    templateUrl: 'user.html',
    params: { // define param config
      // define userId default value as the result of an injected function
      userId: function(myservice) { 
        return myservice.defaultUserId(); 
      } 
    }
  });
});

// ridiculous service provides the value for the default user id
app.service("myservice", function() { 
  return { 
    defaultUserId: function() { return 3; }
  };
});

// load some data, INJECT $urlMatcherFactory!
app.run(function($rootScope, $state, $urlMatcherFactory) {
  $rootScope.users = [ 'user 0', 'user 1', 'user 2', 'user 3', 'user 4'];
 });

Caveat: in 0.2.11 you must inject $urlMatcherFactory somewhere!

Upvotes: 4

Related Questions