Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: $watch from controller for changes in properties created with ng-repeat

Tags:

angularjs

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.

like image 653
GN. Avatar asked Dec 04 '25 05:12

GN.


1 Answers

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.

like image 57
Alex Choroshin Avatar answered Dec 05 '25 21:12

Alex Choroshin