angular-restmod icon indicating copy to clipboard operation
angular-restmod copied to clipboard

$fetch from loaded set

Open jimmybaker opened this issue 10 years ago • 5 comments

Is there a way to $fetch from a loaded set rather than fetching from a resource? For example, I have all of my categories loaded in my controllers already, but each of my products has a "category" association that's not returned with the product resource. I would be nice to use the product.category.id to fetch from the loaded set of categories that I already have.

jimmybaker avatar Sep 08 '14 15:09 jimmybaker

+1 Currently looping though loaded set to find the model I want, would be nice if there was a built in way.

chris-hanson avatar Sep 17 '14 06:09 chris-hanson

Take a look at the SharedModel plugin, if you make your category model shared and load all categories using a collection, then categories loaded in the collection will be automatically loaded into reference relations (belongsTo or belongsToMany).

iobaixas avatar Sep 23 '14 15:09 iobaixas

@chris-hanson Have you tried this yet? I'm looking for example usage now.

jimmybaker avatar Nov 05 '14 15:11 jimmybaker

@jimmybaker I have on simple models and it was pretty straight forward. Haven't tried it with relations.

You just need to mix the SharedModel plugin into the model.

var Product = restmod.model('/api/products').mix('SharedModel');

var products = Product.$search(); // returns 3 products with ids 12, 55 and 60

........

products.$find(100); // XHR to /products/100
products.$find(55); // no XHR

Note that my dist directory from bower didn't have the shared.js file, i grabbed it from src/plugins. I think that may be a bug with the build.

chris-hanson avatar Nov 05 '14 23:11 chris-hanson

What would be the best way to do this the other way around?

I have a collection of playlists that contain a reference to audio files. Playlist and Audiofile are separate models. Playlist has a relation belongsTo with the Audiofile. Multiple playlists can re-use one audiofile. So I used the SharedModel for Audofile.

So far, so good. But when I edit a playlist, I fetch all Audiofile objects in a $collection. The system re-uses the existing cache, but the $scope for the existing models in de cache is wrong.

Is there any way to use a model in both a $collection and as relation to another model?

ebuzzz avatar Nov 07 '14 13:11 ebuzzz