4

I have next 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 names of the items. Is there a way in angularjs to automatically update strings in group > items, when the name of the particular item change. (Is there a way to connect particular parts of the json model?)

Thank you.

1 Answer 1

3

You can set up a deep $watch for each item in the item array. When the item changes, iterate over the group items, 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 Fiddle

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.