Reputation: 301
i am using ui-router for my SPA but I am having issues with the states. My state is setup as below
$stateProvider.state('product', {
url: '/product/:category/:product',
templateUrl: 'src/app/product/product.tpl.html',
controller: 'ProductCtrl'
});
But the issue I am having is that when I go to /product/cat-one my controller handles the fact there is no product set, then when i go to /product/cat-one/product-one my controller again handles the fact there is a product present, which all works well.
The problem im facing is that if i go to /product/cat-two from /product/cat-one/product-one the :product persists and the url ends up being /product/cat-two/product-one.
Can anybody point me in the right direction on this one please?
This is my controller for reference:
.controller( 'ProductCtrl', function ( $scope, $stateParams, ProductService ) {
$scope.categoryId = $stateParams.category;
$scope.productId = $stateParams.product;
$scope.isProduct = false;
if ($scope.productId) {
$scope.isProduct = true;
$scope.item = ProductService.getProduct($scope.categoryId);
} else {
$scope.item = ProductService.getCategory($scope.categoryId);
}
})
Thanks in advance
Upvotes: 0
Views: 288
Reputation: 33171
It really looks like you should be handling this route setup hierarchically:
$stateProvider
.state('category', { url: '/product/:category', templateUrl: 'src/app/product/product.tpl.html', controller: 'ProductCtrl' })
.state('category.product', { url: '/:product', templateUrl: 'src/app/product/product.tpl.html', controller: 'ProductCtrl' });
Now I am not sure on your requirements, but it also might be a good idea to have another parent state ('/product') that abstracts the reused functionality of both categories and products.
Ok, so it looks like the requirements are for showing a single product and single category. I would suggest having a good read of the ui-router documentation when you get a chance. To get the functionality you desire, you should be using a separate template and controller for categories and products.
If you want to completely replace the category page with the product page, then the states should not be hierarchical, however if they borrow reused functionality you could have a parent state to both types that can implement this reusability (but I would more likely use a service here).
So the resulting route definition would be as follows:
$stateProvider
.state('category', { url: '/product/:category', templateUrl: 'src/app/product/category.tpl.html', controller: 'CategoryCtrl' })
.state('product', { url: '/product/:category/:product', templateUrl: 'src/app/product/product.tpl.html', controller: 'ProductCtrl' });
Note that you now need a template and controller for each type.
Upvotes: 1