2014-02-27 30 views
28

我正在構建一個相當簡單的AngularJS應用程序,但出於簡單的原因,我寧願不使用路由(如果可能),只從服務器返回單獨的Angular頁面。從本質上講,只能使用Angular的'小部件'的佈局和功能,而不是在頁面之間移動。角度 - 從控制器中的URL路徑返回ID

雖這麼說,我已經花了幾個小時試圖獲得一個ID走出當前URL的,所以:

/Tickets/:id 

所有我想在我的控制做的,是從URL獲得ID,然後將其傳遞給工廠。 (以下是使用僞代碼的示例)

app.controller('ticketController', ['$scope', '$route', 
    function ($scope, $route, $location) { 
     //Get ID out of current URL 
     var currentId = someFunction().id; 
     factory.callFactory(ID); 
    }]); 

我也試過創建路由,但返回的對象似乎沒有提供獲取ID的方法。

app.config(['$routeProvider', function ($routeProvider) { 
    $routeProvider 
    .when('/tickets/:id', 
     { 
      templateUrl: '/partials/edit', 
      controller: 'ticketController' 
     } 
    ); 
}]); 

不知道我在做什麼錯。

This doesn't seem to work for me

This also doesn't seem to work, but I may be doing something wrong

回答

42

嘗試$routeParams代替:

app.controller('ticketController', ['$scope', '$routeParams', 
    function ($scope, $routeParams) { 
     //Get ID out of current URL 
     var currentId = $routeParams.id; 
}]); 
+6

您需要安裝ngRoute這個工作: HTTPS://docs.a ngularjs.org/api/ngRoute – Magne

+0

如何使用$ location.path(「/ products /」+ category.id); ? –

18

如果您正在使用ui-router所以儘量$stateParams

app.controller('ticketController', ['$scope', '$stateParams', 
    function ($scope, $stateParams) { 
     //Get ID out of current URL 
     var currentId = $stateParams.id; 
}]); 
+0

如何使用$ location.path(「/ products /」+ category.id)如何獲取它; ? –