通过$ routeParams过滤操作

时间:2013-11-27 23:56:37

标签: angularjs

我尝试构建类似于Rails方式的路由。我有一些类似的设置路线:

$routeProvider.when('/posts', {
  controller: 'PostsCtrl',
  templateUrl: '/views/posts.html'
});
$routeProvider.when('/posts/new', {
  controller: 'PostsCtrl',
  templateUrl: '/views/posts.html',
  doNew: true
});
$routeProvider.when('/posts/:postID', {
  controller: 'PostsCtrl',
  templateUrl: '/views/posts.html'
});
$routeProvider.when('/posts/:postID/edit', {
  controller: 'PostsCtrl',
  templateUrl: '/views/posts.html',
  doEdit: true
});

PostCtrl底部有以下内容:

if ($routeParams.doNew) {
  console.log('action: new');
} else if ($routeParams.doEdit) {
  console.log('action: edit', $routeParams.postID);
} else if ($routeParams.libraryID) {
  console.log('action: show', $routeParams.postID);
} else {
  console.log('action: index');
}
当路径为action: show/posts/new/posts/2时,会打印

/posts/2/edit。我可以过滤什么让控制器路由到适当的操作?

2 个答案:

答案 0 :(得分:2)

只需添加解决方案即可轻松完成:

$routeProvider.when('/posts', {
  controller: 'PostsCtrl',
  templateUrl: '/views/posts.html'
  resolve: {
       action: function(){return 'list';}
  }
});
$routeProvider.when('/posts/new', {
  controller: 'PostsCtrl',
  templateUrl: '/views/posts.html'
  resolve: {
       action: function(){return 'new';}
  }
});

等。

然后您可以将action注入您的控制器:

controller('PostCtrl', function($scope, action){
    if(action==='new'){
       console.log('new');
     }
});

答案 1 :(得分:1)

我想出了一种更简单的方法来实现Rails启发的操作。

定义路线:

$routeProvider.when('/posts', {
  templateUrl: '/views/posts/index.html',
  controller: 'PostsCtrl'
});
$routeProvider.when('/posts/new', {
  templateUrl: '/views/posts/index.html',
  controller: 'PostsCtrl',
  action: 'new'
});
$routeProvider.when('/posts/:postID', {
  templateUrl: '/views/posts/index.html',
  controller: 'PostsCtrl',
  action: 'show'
});
$routeProvider.when('/posts/:postID/edit', {
  templateUrl: '/views/posts/index.html',
  controller: 'PostsCtrl',
  action: 'edit'
});

然后为$routeChangeSuccess添加一个事件处理程序:

app.run(['$rootScope', '$route', function ($rootScope, $route) {
  $rootScope.$on('$routeChangeSuccess', function (currentRoute, previousRoute) {
    if ($route.current.action) {
      $rootScope.action = $route.current.action;
    }
  });
}]);

然后在您的控制器中,您可以分支$scope.action

if ($scope.action === 'new') {
  $scope.newPost();
} else if ($scope.action === 'show') {
  Post.get($routeParams.postID).then($scope.showPost);
} else if ($scope.action === 'edit') {
  Post.get($routeParams.postID).then($scope.editPosts);
}

通常我可能会为这些路线设置单独的控制器,但是我正在构建的应用程序上; newshowedit在所有“帖子”的索引上以模式显示。

相关问题