How to automatically update related json parts using angularjs

I have the following json structure:

{
"items": [
    {"name":"item1"},
    {"name":"item2"},
    {"name": "item3"}
],
"groups": [{
    "name": "group1",
    "items": ["item1", "item3"]
},
{
    "name": "group2",
    "items": ["item2", "item3"]
},
{
    "name": "group3",
    "items": ["item1", "item2"]
}]

}

As you can see in my groups, I have element names. Is there a way in angularjs to automatically update rows in group> items when the name of a particular item changes. (Is there a way to connect certain parts of the json model?)

Thank.

+4
source share
1 answer

You can configure deep $ watch for each element in the array of elements. When an element changes, iterate over the elements of the group and replace the old name with the new name:

angular.forEach($scope.model.items, function (item) {
    $scope.$watch(function () { return item; }, function (newVal, oldVal) {
        angular.forEach($scope.model.groups, function (group) {
            var items = group.items;
            var itemIndex = items.indexOf(oldVal.name);
            if (itemIndex >= 0) {
                items[itemIndex] = newVal.name;
            }
        });
    }, true);
});

Demo script

+3
source

All Articles