Object parameters in url using angular ui-router

I need to build a state url based on an object. Basically I want this state:

{
  id: 1,
  f: {
    "5": [
      "1",
      "7"
    ],
    "7": [
      "3",
      "6"
    ]
  }
}

      

To convert it to this url:

http://localhost/resource/1?f[5][]=1&f[5][]=7&f[7][]=3&f[7][]=6

      

How to specify such url pattern with ui-router config and how to get into this state?

Edit: I didn't quite understand how or why I wanted this.

The main idea is to create a filter for some data on the page. I would like users to be able to bookmark a page with filters applied.

I haven't invented a specific URL format, this is the standard way of providing arrays in request parameters for PHP. PHP parses the request with parse_str()

, for example:

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"
    }
  }
}

      

What I want to do is call $state.go()

with my filter parameters (something like the state object above) and make ui-router change the url and state to these parameters in that particular url format.

I'm open to suggestions if there is a better way to do this.

+3


source to share


2 answers


Use a parameter of type "json", which encodes objects as json, or create your own parameter type, which encodes the way you describe.

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

      



or

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

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

      

+5


source


I'm not sure why you want your data to be sent along with the url (you should use a service instead). But this is how you send parameters from the url to switch to a different state. The "parameter" below is the object to be sent:

In the controller that contains the object:

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

      

On your routes :

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

      



In your HTML you want to redirect from:

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

      

The controller that handles the new redirected state:

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

      

I'm sure you can customize the code to your requirements.

+1


source







All Articles