Shirgill Farhan Ansari Shirgill Farhan Ansari - 3 months ago 12
AngularJS Question

How to watch all properties of an object which is generated dynamically?

Consider the snippet:

<div ng-app="myApp" ng-controller="myCtrl">

<table>
<tr ng-repeat = "value in array" >
<td><input ng-model="formdata[value]" /></td>
<td>{{value}}</td>
<td>{{formdata[value]}}</td>
<td>{{data}}</td>
</tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {


$scope.array = [1, 2, 3, 4, 5];
$scope.$watch("formdata",
function() {
// some code goes here
}, true
);
});
</script>


The ng-model for each row is generated dynamically as seen clearly.

formdata[1]
formdata[2]
formdata[3]
formdata[4]
formdata[5]


Now I want to put a watch on all the properties of this object(formdata). I did like above but the watch never gets fired.

Please suggest.

Answer

You didn't create formdata in the scope, so ng-repeat creates it, in its own child scope. And the formdata is thus not in your scope, and thus can't be watched.

I would start at 0 rather than 1, and initialize the array in the scope:

$scope.formdata = [];