现在,$ location服务正在阻碍。假设有人想为多条路线使用相同的控制器,但期望成功的“保存”目的地路线会有所不同。
.when('/sponsors/:sponsorId/games/add', {templateUrl: 'partials/games/create',controller: 'GameCreateCtrl', access: 'sponsor'})
// an admin can see all the games at
.when('/admin/games/add', {templateUrl: 'partials/games/create',controller: 'GameCreateCtrl', access: 'admin'})
任一动作成功时都会显示游戏。路线只是父路径。 例如/ admin / games或/ sponsors /:sponsorId / games。
$ location服务似乎不支持相对路径$ location.path('..')。应该是? 在这种情况下重用GameCreateCtrl的最佳方法是什么?
$scope.save = function () {
GameService.save($scope.game).$promise.then(function(res){
console.log(res);
growl.addSuccessMessage("Successfully saved game: " + $scope.game.name);
console.log("saving game by id:" + $scope.game._id);
var path = $location.path();
$location.path(path.replace('/add', '')); // this seems like a hack
});
}
答案 0 :(得分:3)
您可以使用resolve
:
.when('/sponsors/:sponsorId/games/add', {
templateUrl: 'partials/games/create',
controller: 'GameCreateCtrl',
resolve: {
returnUrl: function($routeParams){
return '/sponsors/' + $routeParams.sponsorId + '/games';
}
}
})
.when('/admin/games/add', {
templateUrl: 'partials/games/create',
controller: 'GameCreateCtrl',
resolve: {
returnUrl: function(){
return '/admin/games';
}
}
})
在控制器中:
app.controller('myCtrl', function($scope, returnUrl){
$scope.save = function () {
GameService.save($scope.game).$promise.then(function(res){
// ...
$location.path(returnUrl); // this seems like a hack
});
};
});
您正在根据路由向控制器传递不同的returnUrl
参数。
答案 1 :(得分:1)
我要感谢海报karaxuna的解决方案。这是我接受的答案。但是,处理其他选项通常很有帮助。
另一种解决方法是创建一个全局函数。
function getParentPath($location) {
if ($location.path() != '/') /* can't move up from root */ {
var pathArray = $location.path().split('/');
var parentPath = "";
for (var i = 1; i < pathArray.length - 1; i++) {
parentPath += "/";
parentPath += pathArray[i];
}
return parentPath;
}
}
这适用于编辑/添加遵循路线位置的休息样式的情况。在这些情况下,parentPath将始终返回所有记录的复数列表 并且可能在根范围中添加方法
$rootScope.goParentPath = function ($location) {
$location.path(getParentPath($location));
}
控制器内的函数可以调用getParentPath函数。 e.g。
$scope.cancel = function() {
$scope.goParentPath($location)
}
我实际上倾向于考虑将第一个答案与getParentPath结合起来的方法。
为了简洁起见,路由将使用resolve callout,但在许多情况下使用parentPath函数。例如:
.when('/admin/games/:id', {templateUrl: 'partials/games/edit', controller: 'EditGameCtrl', access: 'admin',resolve:{returnUrl: getParentPath}})
.when('/admin/games/add', {templateUrl: 'partials/games/create', controller: 'EditGameCtrl', access: 'admin', resolve:{returnUrl: getParentPath}})