0

I am building my first app in AngularJs.

Here is the plunkr with what I've done so far. The user should be able to add new websites and group them in groups. Groups are also made by the user. Any time the new group is created it is available for new websites. What app should also do is to update group objects with newly assigned websites... and this is where I fail.

Here is how json should look like:

{
"sites": [
  {
    "url": "http://sfdg",
    "id": 0,
    "groups": [
      {
        "name": "adsf",
        "id": 0
      }
    ]
  }
],
"groups": [
  {
    "name": "adsf",
    "id": 0,
    "sites": [//sites assigned
     ]
  }
]

}

In the plunkr code I used push but that just adds new group...

Could you please direct me to the right way of achieving this.

Thanks!

4
  • You want to add a sites array to each group which contains all the sites in that group? Commented Jul 11, 2013 at 16:54
  • @robertklep yes. So, I create a group, than I create a website and check the group, the group should update with that site Commented Jul 11, 2013 at 16:57
  • With your current setup, you're going to get circular references (because a website object refers to a group object, which refers to the website object, etc...). I think you'd better save just id's to sites/groups instead (plnkr). Commented Jul 11, 2013 at 17:08
  • @robertklep great! yeah i think id's should suffice as i need to filter them by groups later... you want to post it as an answer so i can accept it? Commented Jul 11, 2013 at 17:20

1 Answer 1

1

To prevent circular references (a website object refers to a group object that refers to the website object, etc...), I would store id's to the relevant objects instead.

First, when creating a new group, add an empty sites array to it:

function createGroup(newGroup) {
  newGroup.sites = [];          // <-- add empty array of sites
  $scope.groups.push(newGroup);
  newGroup.id = groupIdSeq;
  groupMap[newGroup.id] = newGroup;
  groupIdSeq++;
  return newGroup;
}

Then, when you create a new site, update each group to which the site is added:

  function createSite(newSite, groups) {
    $scope.sites.push(newSite);
    newSite.id = siteIdSeq;
    sitesMap[newSite.id] = newSite;

    // instead of storing the groups array, only store their id:
    newSite.groups = groups.map(function(group) { return group.id });

    // and add this new sites id to the groups' sites array.
    groups.forEach(function(group) {
      group.sites.push(newSite.id);
    });

    siteIdSeq++;
    return newSite;
  }

(updated plunker here)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.