Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested parameters in angular query

I have a basic angular resource (angular 1.0.7):

app.factory "User", [ "$resource", ($resource)->
  $resource "/users/:id", { id: '@id' }, {
    index:     { method: 'GET', isArray: false }
  }
]

I can pass parameters like:

User.index({ foo: 1, bar: 2 })

But I need to pass nested parameters:

User.index({ foo: { bar: 1 } })

And this fails because it sends:

/users?foo=%5Bobject+Object%5D

I tried:

User.index({ foo: JSON.stringify({ bar: 1 }) })

But obviously parameters are not recognised on the server side (mere strings) and I'd like to avoid the hassle of parsing there.

Do you have an elegant solution to this issue?


With jQuery I'd have done:

$.get("/users", { foo: { bar: 1 } } )

Producing:

/users?foo%5Bbar%5D=1

Perfectly interpreted by the server.


Seems like a known issue (here too), let's stick to an ugly patch from now...

like image 252
apneadiving Avatar asked Sep 03 '13 09:09

apneadiving


1 Answers

Not as elegant as the changes coming to Angular but you should be able to solve this by setting your param with the results of a function:

User.index.get({ "foo": (function () { 
    return JSON.stringify({ bar: 1 });
})() } );

Results in a HTTP request similar to what you were looking for:

?foo=%7B%22bar%22:1%7D

The entire angular example:

var app = angular.module('myApp', ['ngResource']);
var restUrl = window.location + 'echo/json/';

app.factory('User', function($resource, $http){
    return {
        index: $resource(restUrl)
    }               
});

function RestCtrl($scope, User) {
    $scope.url = restUrl;
    User.index.get({ "foo": (function () { 
        return JSON.stringify({ bar: 1 });
    })() } );
}

http://jsfiddle.net/pherris/U8F8G/6/

like image 131
pherris Avatar answered Sep 24 '22 06:09

pherris