urlMatcherFactory编译URL

时间:2014-12-16 21:10:35

标签: angularjs angular-ui angular-ui-router

我想使用urlMatcherFactory将URL参数解析为该对象。

URL:

/home/1?param1=tt

JS:

var urlMatcher = $urlMatcherFactory.compile("/home/:id?param1&param2");
var matched = urlMatcher.exec($location.url());

执行此代码后,我只获得1个字段:id为1?param1=tt

的id

在这种情况下,我希望得到2个字段:id ==> 1和param1 ==> TT

2 个答案:

答案 0 :(得分:3)

要解析URL搜索参数,我们必须将这些参数可分离地传递给exec函数:

var urlMatcher = $urlMatcherFactory.compile("/home/:id?param1&param2");
var matched = urlMatcher.exec($location.path(), $location.search());

答案 1 :(得分:0)

您可以在urlMatcherFactory文件中阅读评论,您可以看到以下评论来解析网址上的查询参数:

/*
 * Wraps an existing custom Type as an array of Type, depending on 'mode'.
 * e.g.:
 * - urlmatcher pattern "/path?{queryParam[]:int}"
 * - url: "/path?queryParam=1&queryParam=2
 * - $stateParams.queryParam will be [1, 2]
 * if `mode` is "auto", then
 * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
 * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
*/

所以,我认为您需要使用urlMatcher作为以下内容:

var matched = urlMatcher.exec($location.url(), {mode: 'auto'});

详细了解URL-Routing#urlmatcherfactory-and-urlmatchers