http://jsfiddle.net/EjyW4/
Essentially, I am trying to post an array of objects from the client using AngularJS with the resources module, and instead of sending a JSON object, Angular is sending a useless toString representation over the wire.
Unfortunately, the code in the fiddle itself doesn't do much -- the intent is outlined here with more context, though it still is very raw and do not yet resemble anything looking like the right way) But this seems to be an angular issue rather than grails, at least from looking at the Chrome console.
Query String Parameters:
callback:JSON_CALLBACK
tests:%5Bobject+Object%5D,%5Bobject+Object%5D
There seems to be an angular.toJson -- http://docs.angularjs.org/api/angular.toJson -- but it doesn't seem to work in this case. The documentation I've seen doesn't seem to cover more than sending a basic int. If I have to, I'll send over a comma separated string, but this seems like it should be a common use case.
The $resource function actually returns a new $resource object constructor, which you then set properties on, then call methods like save on.
So your problem in your fiddle is you're trying to save a $resource with no data set on it! All you have is a config property, tests, which it doesn't know what to do with.
You instead want to:
Set up your constructor for a new resource using $resource factory/method.
Create a new instance of your new resource.
Set a property on it (eg myNewResource.tests = $scope.tests);
Save it (myNewResource.$save())
http://jsfiddle.net/EjyW4/2/
It looks like what you were trying to do originally is better suited for $http (I put an example of that in the fiddle too).
Related
New to backbone/marionette, but I believe that I understand how to use backbone when dealing with CRUD/REST; however, consider something like results from a search query. How should one model this? Of course the results likely relate to some model(s), but they are not meant to be tied to said model(s).
Part of me thinks that I should use a collection using a model that doesn't actually sync with a data store through the server, but instead just exists as a means of a modeling a search result object.
Another solution could be to have a collection with no models and just override parse.
I assume that the former is preferred, but again I have no experience with the framework. If there's an alternative/better solution than those listed above, please advise.
I prefer having one object which is responsible for both request and response parsing. It can parse the response to appropriate models and nothing more. I mean - if some of those parsed models are required somewhere in your page, there is something that keeps reference to this wrapper object and takes models from response it requires via wrapper methods.
Another option is to have Radio (https://github.com/marionettejs/backbone.radio) in this wrapper - you will not have to keep wrapper object in different places but call for data via Radio.
Angular novice here.
I have a REST API of my own creation that supplies data (data that has been sourced from a 3rd party and undergone very little transformation). The "heaviest" endpoint returns over 100 key-value pairs in JSON.
I also have a template that I made by hand that has places for all of this data to go. The thing is, a lot of the data my API returns must undergo light transformations before being stuck in the template.
For example:
a string must have underscores replaced with spaces
an ID must be resolved to both a string and an image (both retrievable from REST API) that get placed in different parts of the template.
This has to be done multiple times per page; the endpoint returns an array, with each entry containing the 100+ key-val pairs.
But I am unsure of how to handle the transforms that need to occur between API and page display. Should I write a controller that grabs this data from an Angular service (that in turn talks to my REST api), and then generates strings (to be placed in the template) that get placed in $scope properties? And then write a directive for each $scope element that I want to be placed in the page, and fill in my template with those directive?
It seems strange to write things this way since I'm not sure how that's different from just using curly braces to directly reference the $scope properties. Should I move more of my work into the directive code and trim down the controller, or what?
In short, I am uncertain of how to apportion the workloads and data among the tools Angular provides. I realize there are a lot of options here, but nothing I've read so far jumps out at me for how to organize this properly. If it seems like there's something I'm missing, feel free to just tell me to hit the books again, or read more on a certain subject of the framework.
I'm new to AngularJS and I am currently building a webapp using a Django/Tastypie API. This webapp works with posts and an API call (GET) looks like :
{
title: "Bootstrap: wider input field - Stack Overflow",
link: "http://stackoverflow.com/questions/978...",
author: "/v1/users/1/",
resource_uri: "/v1/posts/18/",
}
To request these objects, I created an angular's service which embed resources declared like the following one :
Post: $resource(ConfigurationService.API_URL_RESOURCE + '/v1/posts/:id/')
Everything works like a charm but I would like to solve two problems :
How to properly replace the author field by its value ? In other word, how the request as automatically as possible every reference field ?
How to cache this value to avoid several calls on the same endpoint ?
Again, I'm new to angularJS and I might missed something in my comprehension of the $resource object.
Thanks,
Maxime.
With regard to question one, I know of no trivial, out-of-the-box solution. I suppose you could use custom response transformers to launch subsidiary $resource requests, attaching promises from those requests as properties of the response object (in place of the URLs). Recent versions of the $resource factory allow you to specify such a transformer for $resource instances. You would delegate to the global default response transformer ($httpProvider.defaults.transformResponse) to get your actual JSON, then substitute properties and launch subsidiary requests from there. And remember, when delegating this way, to pass along the first TWO, not ONE, parameters your own response transformer receives when it is called, even though the documentation mentions only one (I learned this the hard way).
There's no way to know when every last promise has been fulfilled, but I presume you won't have any code that will depend on this knowledge (as it is common for your UI to just be bound to bits and pieces of the model object, itself a promise, returned by the original HTTP request).
As for question two, I'm not sure whether you're referring to your main object (in which case $scope should suffice as a means of retaining a reference) or these subsidiary objects that you propose to download as a means of assembling an aggregate on the client side. Presuming the latter, I guess you could do something like maintaining a hash relating URLs to objects in your $scope, say, and have the success functions on your subsidiary $resource requests update this dictionary. Then you could make the response transformer I described above check the hash first to see if it's already got the resource instance desired, getting the $resource from the back end only when such a local copy is absent.
This is all a bunch of work (and round trips) to assemble resources on the client side when it might be much easier just to assemble your aggregate in your application layer and serve it up pre-cooked. REST sets no expectations for data normalization.
According the Backbone.js documentation Model-parse does the following:
parse is called whenever a model's data is returned by the server, in
fetch, and save.
To augment models I've already loaded I use Model.parse(). I accomplish this by using fetch to make an additional request for data, then use that data to add properties to an existing model.
Example:
the fetch object is {age: 19}
after the parser will be {age: 19, isAdult: true}
When I perform the save request, in the PUT request I also have other parameters not needed (for example isAdult). I would like to have the original model (without additional parameters in PUT request).
What is the best way to achieve my goal in Backbone?
If I understand your question correctly ....
When backbone talks to a server using a save it sends a complete respresentation of the model. As the docs put it :
The attributes hash (as in set) should contain the attributes you'd
like to change — keys that aren't mentioned won't be altered — but, a
complete representation of the resource will be sent to the server.
So the default behavior is to send the complete model. If you want to implement you're own logic you're going to have to override the sync method. Dig through the expanded backbone code a bit and you'll see this comment above sync :
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the model in question.
I would use the default implementation of sync as my starting point.
So GET forms make the usual urls like
.../search/?q=apple
Can you make a form create urls like
.../search/q:apple/
Thanks, guys. I've found a different solution. I just submit the form as a POST and in the controller's action I read the post data and create a url with the post data as named params and then $this->redirect('...'); to it.
The methods to create these URL's can be found here: http://book.cakephp.org/view/842/url
If I understand you correctly, you're not looking to create a different URI, per se, but rather to serialize the form data in a different way. In other words, you're interested in modifying the query string rather than the URI itself.
As far as I know, that's the way that forms serialize their data and there's no way to truly override this behavior. If you really want to do this, I suspect you'll have to capture the submit event, manually serialize the form data into the format you want, append that format to the form's action value, make a custom request to the page (via location.href, etc.) and return false so that the form itself never actually gets submitted.
Of course, you could also submit via Ajax where you have a little more control.
I'm not aware of any other way to do what I think you're asking.