Bojana Šekeljić
Bojana Šekeljić

Reputation: 1056

Trouble with updating object properties in AngularJs

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!

Upvotes: 0

Views: 46

Answers (1)

robertklep
robertklep

Reputation: 203231

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)

Upvotes: 1

Related Questions