how to update elements containing relation

52 Views Asked by At

I have scope like below

 $scope.phones = [
    {
        id: 4,
        name: "nokia",
        accessories: [
            {id: 1, name: "headset"},
            {id: 3, name: "keyboard"},
            {id: 5, name: "charger"}
        ]
    },
    {
        id: 5,
        name: "samsung",
        accessories: [
            {id: 5, name: "charger"}
        ]
    },
    {
        id: 6,
        name: "iphone",
        accessories: [
            {id: 1, name: "headset"},
            {id: 5, name: "charger"}
        ]
    }
];

For example they are displayed like

-> Phone name
    -> accesories

Now my case

If I update accessory that is in relation with phone I want to update records that are displayed but only those that are in relation with updated accessory. I don't want to update whole action view but only records that are bound with the updated accessory

How can I do that ?

// edit

I've created a manual workaround

 $scope.editAcc = function (idx) {
            for(var i = 0; i < $scope.phones.length; i++) {
                var tmpPhone = $scope.phones[i];
                for(var j = 0; j < tmpPhone.accessories.length; j++) {
                    var acc = tmpPhone.accessories[j];
                    if(acc.id == idx) {
                        acc.name = acc.name + " Z";
                    }
                }
            }

// var acc = $scope.accessories[idx]; // acc.name = acc.name + " X"; };

But IMO there should be some function to do that

1

There are 1 best solutions below

1
On

I don't think there is a built-in way to update the value by JSON path, but you can at least use angular.forEach() to loop through the collections:

$scope.editAcc = function (idx) {
    angular.forEach($scope.phones, function (t) {
        angular.forEach(t.accessories, function(acc){
            (acc.id == idx) ? (acc.name += " Z") : null;
        });
    });
}

DEMO