Reputation: 9839
How do you listen in an angular controller to changes in a child properties? And from that controller know which child was changed?
HTML
<div ng-app ng-init='people = [{name: "bill", age: "11"}, {name: "jim", age: ""}, {name: "ryan", age: ""}]'>
<h1> msg: {{ msg }} </h1>
<table>
<tr ng-repeat='person in people'>
<td>
{{ person.name }}
<input ng-model='person.name'>
</td>
</tr>
</table>
</div>
edit
For instance, if I wanted to add .highlight
class to every <td>
that has a value for age how would I do that? I am new to Angular, but I think $watch would be the right way to do this? Because the value might be changed in the UI but changes could come from elsewhere.
The parent controller would need the value changed, and pinpoint which one changed and add the class.
Upvotes: 3
Views: 2689
Reputation: 27104
You can easily apply a class based on the person's age as follows:
<td ng-class ='{highlight : person.age}'>
Angular will do the magic for you, no need to manually watch for changes.
See http://jsfiddle.net/GAQvM/1/
EDIT: Old answer on $scope.$watchCollection
:
It does work when you spell out the actual items to watch:
$scope.$watchCollection('[people[0].name, people[1].name, people[2].name]',
changeHappened);
I realise that this is not exactly feasible for large collections, but I think it points out that the watch is shallow, only one level deep.
The documentation for $watchCollection says (my emphasis):
Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)
Upvotes: 0
Reputation: 6187
when deep $watch is needed, but not for the entire object, you can strip out irrelevant data, this way you make the comparison much faster.
Example: (solution by Karl Seamon)
$scope.$watch(function($scope) {
return $scope.people.
map(function(obj) {
return obj.name
});
}, function (newVal) {
$scope.msg = 'person name was changed';
}, true);
Live working example: http://jsfiddle.net/choroshin/uhrQ4/
For more information take a look at my blog post.
Upvotes: 4