AngularJs Routing with parameters
Asked Answered
C

2

13

Can someone explain how I can route to a Url using parameters?

E.g. id like to click on a product and open more info of the product by Id.

My Routing so far ...

        angular.module('shop', ["customFilters", "cart", "ngRoute"])
        .config(function ($routeProvider){

            $routeProvider.when("/complete", {
                templateUrl: "../app/views/orderComplete.html"
            });

            $routeProvider.when("/placeorder", {
                templateUrl: "../app/views/placeOrder.html"
            });

            $routeProvider.when("/checkout", {
                templateUrl: "../app/views/checkoutSummary.html"
            });

            $routeProvider.when("/products", {
                templateUrl: "../app/views/productList.html"
            });

            $routeProvider.when("/product:", {
                templateUrl: "../app/views/product.html"
            });

            $routeProvider.otherwise({
                templateUrl: "../app/views/productList.html"
            });

        });

So By clicking ...

<a class="btn btn-default" href="#/product/{{item.id}}">More Info</a>

Id like to be routed to product/{{id}}.html ...

Can someone advise what I am missing in ...

       $routeProvider.when("/product:id", {
            templateUrl: "../app/views/product.html"
        });
Cessation answered 1/10, 2016 at 21:59 Comment(1)
use github.com/angular-ui/ui-routerFoucault
B
21

2 things, but you are basically there.

First you are missing a slash before the URL param. Happens to the best of us.

routeProvider.when("/product/:id", {
    templateUrl: "../app/views/product.html"
});

Secondly you should use ng-href instead href when you have dynamic URL params.

<a ng-href="#/product/{{item.id}}">More Info</a>
Bradstreet answered 1/10, 2016 at 22:9 Comment(2)
Thanks dude, an extra pair of eyes is always the key after hours on coding. Appreciate the help @enzey!Cessation
i have a question, what if you have /product/new ... how do you add it?Damal
S
8

I thinks this issue is duplicate, see response How to pass parameters using ui-sref in ui-router to controller

you can send paramters to state name as home({foo: 'fooVal1', bar: 'barVal1'}) with a url '/:foo?bar' see this exemple:

$stateProvider
    .state('home', {
      url: '/:foo?bar',
      views: {
        '': {
          templateUrl: 'tpl.home.html',
          controller: 'MainRootCtrl'

        },
        ...
      }

and send values as:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
Strage answered 1/10, 2016 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.