简体   繁体   English

计算Angular JS路径

[英]Calculating Angular JS route path

I'm using AngularJS 1.2. 我正在使用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 . 我不允许更改为使用 ui-router

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. 几乎可以执行的操作是在字符串原型中添加“ format”函数(如果尚不存在),并允许您以与.NET“ String.Format()”调用相同的方式进行调用。

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. 从理论上讲,您可以仅使用此函数并将其设为String对象上的函数,然后使用参数对其进行调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM