30

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

2 Answers 2

45

Try $routeParams instead:

app.controller('ticketController', ['$scope', '$routeParams',
   function ($scope, $routeParams) {
      //Get ID out of current URL
      var currentId = $routeParams.id;
}]);
Sign up to request clarification or add additional context in comments.

2 Comments

You need to install ngRoute for this to work: docs.angularjs.org/api/ngRoute
How can I get it if I use $location.path("/products/" + category.id); ?
18

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

1 Comment

How can I get it if I use $location.path("/products/" + category.id); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.