2016-10-01 124 views
8

有人可以解释如何使用参数路由到Url吗?AngularJs使用参数路由

E.g. id喜欢点击产品并通过Id打开产品的更多信息。

我的路由到目前为止...

 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" 
      }); 

     }); 

所以通过点击...

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

Id喜欢被路由到产品/ {{ID}}。HTML ...

有人能指教一下我缺少的...

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

使用https://github.com/angular-ui/ui-router – malix

回答

13

2件事,但你基本上在那里。

首先,您在URL参数前缺少一个斜线。发生在我们身上。

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

其次,当你有动态URL参数时,你应该使用ng-href而不是href。

<a ng-href="#/product/{{item.id}}">More Info</a> 
+0

感谢兄弟们,额外的一双眼睛在编码之后总是关键。感谢@enzey的帮助! – ClarkySmiverz77

+0

我有一个问题, 如果你有/产品/新...你如何添加它? –

3

我认为这个问题是重复的,请参阅响应How to pass parameters using ui-sref in ui-router to controller

您可以发送paramters国家名称作为家庭({富: 'fooVal1',巴: 'barVal1'}) 与URL“ /?:富巴” 看到这个为例:

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

     }, 
     ... 
     } 

和发送值:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">