2

I'm using AngularJS 1.2. What is the proper way to build a route path with parameters? String concatenation seems to be the only way, but it doesn't seem to be right.

Supposed I have this route

$routeProvider.when('/my-route/:param1/:param2', ...);

I could manually build that route up like this:

$location.path('/my-route/' + param1 + '/' + param2);

I would expect that I could do something like this:

$route.goTo('/my-route/:param1/:param2', {
   param1: param1,
   param2: param2
});

I am not permitted to changing to use ui-router.

Claies
  • 22,124
  • 4
  • 53
  • 77
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445

1 Answers1

-1

I found something a while back which would probably help, found Here. I've used this a few times, and so far it seems to work pretty well.

Pretty much what this will do is add the "format" function to the string prototype (if it isn't already there) and allow you to call it in the same manner as the .NET "String.Format()" call.

CODE:

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

USAGE:

$location.path(('/my-route/{0}/{1}').format(param1, param2);
//Assuming that param1 and param2 are defined and valid data types

In theory, you could just take this function and make it a function on the String object, and call it with a parameter.

Community
  • 1
  • 1
molson504x
  • 1,180
  • 10
  • 18
  • 1
    this isn't any better than string concatenation for what i'm attempting to accomplish. – Daniel A. White Feb 18 '15 at 16:09
  • You're right, I was mistaken in what you were attempting to do. There was another answer here that appears to have been removed, but I caught them posting a fiddle... https://jsfiddle.net/tuipopenoe/trb98b5b/ – molson504x Feb 18 '15 at 16:20