0

I'm currently handing down JSON data from Rail in the DOM. It looks like this:

> gon.posts
[
  { id: 1, name: "Post 1", related_post_ids: [3] },
  { id: 2, name: "Post 2", related_post_ids: [2, 3] },
  { id: 3, name: "Post 3", related_post_ids: [1, 2] }
]

How would I be able to write some AngularJS (I'm ruby) so that I could execute this pseudocode:

// Using "Post 1" and mapping to its related posts.
> gon.posts[0].related_posts
[
  { id: 3, name: "Post 3", related_post_ids: [1, 2] }
]

// Then being able to do this recursively to make development with the JSON easier:
> gon.posts[0].related_posts[0].related_posts
[
  { id: 1, name: "Post 1", related_post_ids: [3] },
  { id: 2, name: "Post 2", related_post_ids: [2, 3] }
]

It would also be helpful if you could show how to do this via a map or each function with AngularJS.


A user commented that Array.prototype.filter() would be useful, but I'm not looking for a gross solution, I'm looking for the best, minimal, DRYest solution via AngularJS.


Ember Data has a find() method. If I was able to use Ember and load the data up, I would be able to easily search, but I would still need something like an ActiveRecord::Proxy object in JS to be able to handle the delegations and I'm not sure how to meta program new object types in JS.

BenMorganIO
  • 2,036
  • 17
  • 37

1 Answers1

0

You can use angular's build in $filter service for that. Check out this question

How to use a filter in a controller?

Community
  • 1
  • 1
haki
  • 9,389
  • 15
  • 62
  • 110
  • I don't think a filter should go inside of a controller. I have a feeling that might lead to some serious confusion from other developers, especially since its business logic. Is there a better way to use a `$filter` to filter business logic? – BenMorganIO Jan 27 '15 at 07:49
  • Is there a well maintained JS bower package for `$filter`s that would suffice for data modelling? – BenMorganIO Jan 27 '15 at 08:20
  • Haki, can you provide an example using Lodash and where you place the code inside of an Angular application? – BenMorganIO Jan 27 '15 at 08:43
  • Lodash is a very common general purpose library for data and object manipulation in javascript (you might know underscore). It has nothing to do with angular. You can inject it as a value. e.g `app.value('lodash',_)` and then into your controller via regular injection and use the functions as you wish. – haki Jan 27 '15 at 09:41