redirect by routing in angularjs

All we need is an easy explanation of the problem, so here it is.

i have the following requirement:
a list should be displayed for all items with edit and delete link. when user clicks on edit, edit form should appear with textboxes and a save button. now when user edits the data and clicks on the save button the data should be saved and the listing page should appear again with the modified data.
everything works fine but the how do i redirect to the listing page again through routing in angularjs?
below is some of the code:

ROUTING CONTROLLER:

    angular.module('productapp', []).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/productapp', {templateUrl: 'partials/productList.html', controller: productsCtrl}).
        when('/productapp/:productId', {templateUrl: 'partials/edit.html', controller: editCtrl}).
        otherwise({redirectTo: '/productapp'});
}]);

edit form:

    <div>
    <form method="POST">
    <label>Add New Product:</label>
        <input type="text" name="keywords" ng-model="product.name" placeholder="enter name..." value="{{product.name}}">
        <input type="text" name="desc" ng-model="product.description" placeholder="enter description..." value="{{product.description}}">
        <button type="submit" ng-click="save(product.product_id,$event)" >Save</button>
    </form>
</div>

how do i redirect to the same listing page?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You need to inject the $location service in your editCtrl controller.

Then, in your save function add the following to do the redirect (note that the path matches your route).

$scope.save = function (...) {
    // ...
    $location.path('/productapp');
}

This Youtube video might also help you.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply