2016-10-01 121 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'})">