Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Return ID from URL Path in Controller

Tags:

url

angularjs

I am building a rather simple AngularJS app, but for simplicity's sake, I'd rather not use the routing (if possible), and just serve back individual Angular pages from the server. Essentially, use Angular only for layout and functionality of 'widgets' and not for moving between pages.

With that said, I've spent hours trying to get an ID out of the current URL, so:

/Tickets/:id

All I want to do in my controller, is get the ID from the URL, then pass that to a Factory. (below is an example using pseudocode)

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

I've also tried creating routes, but the objects returned don't seem to provide a way to get the ID.

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

Not sure what I'm doing wrong.

This doesn't seem to work for me

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

like image 884
Greg Avatar asked Feb 27 '14 21:02

Greg


2 Answers

Try $routeParams instead:

app.controller('ticketController', ['$scope', '$routeParams',
   function ($scope, $routeParams) {
      //Get ID out of current URL
      var currentId = $routeParams.id;
}]);
like image 121
asgoth Avatar answered Nov 18 '22 12:11

asgoth


If you are using ui-router so try $stateParams:

app.controller('ticketController', ['$scope', '$stateParams',
   function ($scope, $stateParams) {
      //Get ID out of current URL
      var currentId = $stateParams.id;
}]);
like image 18
Omid-RH Avatar answered Nov 18 '22 14:11

Omid-RH