带有角度ui-router的URL中的对象参数

时间:2015-06-09 10:13:39

标签: angularjs angular-ui-router

我需要根据对象构造一个状态URL。基本上我想要这个状态:

parse_str()

要转换为此网址:

php > parse_str('f[5][]=1&f[5][]=7&f[7][]=3&f[7][]=6', $arr);
php > var_dump($arr);
array(1) {
  ["f"]=>
  array(2) {
    [5]=>
    array(2) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "7"
    }
    [7]=>
    array(2) {
      [0]=>
      string(1) "3"
      [1]=>
      string(1) "6"
    }
  }
}

如何使用ui-router配置指定这样的url模式以及如何转换到该状态?

编辑:我并不清楚我想要的方式或原因。

主要思想是为页面上的某些数据创建过滤器。我希望用户能够在应用过滤器的情况下为页面添加书签。

url的具体格式不是我发明的,它是在PHP的查询参数中提供数组的标准方法。 PHP使用$state.go()解析查询,如下所示:

{{1}}

我想要做的是用我的过滤器参数调用{{1}}(类似于上面的状态对象),并让ui-router将url和state更改为这个特定url格式的参数。

如果有更好的方法,我可以接受建议。

2 个答案:

答案 0 :(得分:5)

使用" json" param类型,它将对象编码为json,或者创建一个自定义param类型,用于编码您描述的方式。

.state("foo", { url: "/foo?{queryParam:json}" });

或者

var customType = {
  encode: encodeFn,
  decode: decodeFn
}
    $urlMatcherFactoryProvider.type("phpQuery", customType);

    .state("foo", { url: "/foo?{queryParam:phpQuery}" });

答案 1 :(得分:1)

我不确定您为什么希望将您的数据与url一起发送(您应该使用服务代替)。但是这里是如何使用url发送参数以切换到不同的状态。下面的'参数'是您需要发送的对象:

在包含对象的控制器中:

$scope.parameter = {//whatever object you want
};

在路线中

app.config(function config($stateProvider) {
    $stateProvider.state("example",{
        url: "fooURL/bar=:parameter",
        controller: "FooCtrl as foo",
        templateUrl: "templates/foo.html"
    })
})

在您要重定向的HTML中:

<div ui-sref="example({bar: parameter})">

处理新重定向状态的控制器:

app.controller('FooCtrl', ['$scope', '$stateParams', function($scope, $stateParams) {
    $scope.bar = $stateParams.bar;
}])

我相信您可以根据您的要求调整代码。

相关问题