Angularjs: Same state and url for edit and add page

159 views Asked by At

I want to use the same state for both edit and add page. Here is how my state looks

 .state('editProduct', {
url: "/editProduct/:productId",
data: {title: "Edit product"},
templateUrl: 'views/package/editProduct.html',
controller: 'editProductCtrl',
controllerAs: 'editProduct'
});

Now in my controller, I want to check when I get stateParam "packageId" I get the boolean variable isEditMode = true, else I want to set it isEditMode=false.

Now when my editMode is true I will allow the user to edit product with prepopulated details.

When editMode is false, I want to show a blank product form where a user can create new Product.

Reason for this approach: I want to re-use the HTML page for edit and add product

Issues Faced: I am able to access /editProduct/1 but I am unable to access /editProduct, I am redirected to default route

2

There are 2 answers

0
ThibaudL On

Your are using a pathParam which is a mandatory one ("/:productId"). If you want it to be optionnal, you should use a queryParam :

url: "/editProduct?productId",
0
Rathma On

You need to make your parameter optional, try adding this to your state definition if you are using ui-router version 1.x:

params: {
   productId: null
}