Reputation: 2625
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.
Upvotes: 0
Views: 393
Reputation: 1063
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.
Upvotes: 1