Angular UI-Router解析可选参数

时间:2014-10-23 13:46:03

标签: angularjs angular-ui-router

我有以下路线:

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

我希望将id作为可选参数,如果未定义,则通过服务解析。

因此/project/dashboard也会解析为/project/ID/dashboard

当我简短地查看所有文档和谷歌时,最好的方法是什么?此外,如果有人有任何关于通过网站范围内的服务公开当前所选id的提示,那么我ui-sref的工作会非常棒:)

注意我能通过这个来解决这个问题(但它真的很糟糕,我不喜欢它)

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

1 个答案:

答案 0 :(得分:3)

您想使用默认参数值。

请参阅此插件: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'];
 });

警告:在0.2.11中你必须在某处注入$ urlMatcherFactory!