Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to understand how best to achieve the following in angularjs.

1) I have an array of objects:

$scope.myArray = [{special:false, name:'alice'}, {special:false, name:'bob'}];

if myArray[0].special changes to true, using $watch how can I detect that this was because of a change in element 0 of the array. Everything I have read on $watch deals with notifying that the array as a whole as changed but there is no way to retrieve the element/index of the array that has changed. I want to have this cope with varying lengths of arrays, so it would not suffice to simply have:

$scope.watch('myArray[0].special')

2) I have a dictionary:

$scope.myValues = {id1:{special:false, name:'alice'}, id2:{special:false, name:bob'}};

a similar question - if I was to change myValues.id1.special to true, how could I get the corresponding name field (or know it was id1)?

I would really appreciate any help and guidance here on best practice and what is actually possible with angularjs and $watch (or $watchcollection) with respect to arrays and maps. I think this is similar to question Watch angular array of objects and animate the changed property but I'm also interested to see how to watch across all properties in a dictionary.

Many many thanks in advance.

share|improve this question
    
maybe this can help you answer #1: stackoverflow.com/questions/13980896/… –  Ronnie 24 mins ago

1 Answer 1

A watch listener provides you with both the newValue and the oldValue - so it's your job to compare the two to see what has changed. Since you wish to perform value rather than reference comparison, use $watch with the third parameter set to true:

$scope.$watch( 'myObject', function( newVal, oldVal ){
    // Compare newVal and oldVal here to see what has changed.
}, true);
share|improve this answer
    
I think for arrays this will return the full list of items in each array for both newVal and oldVal. I would then need to scan through each array and compare .special between the two. Just wondering if this is handled automatically by some part of angular such that it would return index 0 instead. –  user1710407 18 mins ago
    
Angular has no way of doing this I'm afraid - such feature would be handy, but it could damage performance whilst not always being needed. What's more, how angular suppose to know what to return? As in, what you want to be provided as a change (the full path, a sub path, etc.) –  Izhaki 15 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.