Stephanie Caldwell
Stephanie Caldwell

Reputation: 647

How do I access a url parameter inside a controller?

I have a controller that needs to access a url parameter. However, I can't figure out how to access the parameter. Here is what I have so far:

Controller:

function CustomerCtrl($scope, $http, $routeParams, $route) {

// var customer_id = $routeParams.id; // this doesn't work
// var customer_id = $route.current.params.id; // this doesn't work
var customer_id = '58'; // this clearly works

$http({
    url: 'customers/'+customer_id+'/info',
    method: "POST"
})
.success(function (data, status, headers, config) { $scope.name = data; })
.error(function (data, status, headers, config) { $scope.status = status; });
}

App:

var customer = {
    name: 'customer',
    url: '/customer',
    abstract: true,
    templateUrl: 'views/customer/customer.html',
    controller: 'CustomerCtrl'
};

var customer_info = {
    name: 'customer.info',
    parent: customer,
    url: '/:id/info'
    views: {
        view1: { templateUrl: "views/customer/view1.html" },
        view2: { templateUrl: "views/customer/view2.html" }
    }
};

$stateProvider
    .state(customer)
    .state(customer_info);

What am I missing?

Upvotes: 3

Views: 641

Answers (2)

Shawn Balestracci
Shawn Balestracci

Reputation: 7530

It's actually even easier than you thought. You're using the ui-router (https://github.com/angular-ui/ui-router) which uses states instead of the default router.

function CustomerCtrl($scope, $http, $routeParams, $route) {

should be:

function CustomerCtrl($scope, $http, $stateParams, $state) {

then:

var customer_id = $stateParams.id; 

Upvotes: 1

Stephanie Caldwell
Stephanie Caldwell

Reputation: 647

I spent all day confusing myself by trying to find an angular solution to this seemingly simple, common problem. Most of you probably already figured this out, but the solution is to just use plain old javascript:

var pathArray = window.location.pathname.split( '/' );
var customer_id = pathArray[3];
$scope.customer_id = customer_id

So simple, yet I feel like an idiot for not thinking about this from the beginning.

Upvotes: 0

Related Questions