简体   繁体   中英

$scope.$watch a particular object inside an array - Angular JS controller

My schema is as below.

Orders {
    customers[{
        customerId: String,
        address: String,
        onlineOrder [{
            items...
        }],
        directOrder [{
            items...
        }]
    }]
}

Now, for some reason(too big to explain) I want a watch function, for any items added to onlineOrder[items] array.

For that, I couldnot write the function like,

$scope.$watch('order.customer[i].onlineOrder[j]')

where i and j are array indices.

Because I want the watch function to be triggered for the current 'i'th customer, for every add/delete/modify of 'j'th online order item

I need help in this.

I would suggest controlling the access to the array you need to watch, so you can be aware of the changes yourself, without the inefficiencies of a $watch . I'm not sure what all you are trying to do with that object, and it what ways it could be manipulated, but lets say it has items added by a user clicking a button( ng-click ).

To control access you could then have the button call a function like so:

<button ng-click="doWork(orderId, customerId, newOnlineOrder)">Add Order</button>

//in your controller
$scope.doWork = function (orderId, customerId, onlineOrder) {
  //do some work to ensure the order is good, then add it to the collection:
  orders[orderId].customers[customerId].push(onlineOrder);
  //notify anything that needs to know it changed
  notifyMyCode(onlineOrder);
};

In this way, you easily know what changed, and you control it being changed maliciously, or by accident, you can validate data before updating your model, and you will know faster and with more certainty that a $watch expression because you control the only way to change the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM