我有以下路线:
$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';
});
答案 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'];
});