0
$scope.arr = [
[["TTT", 23],3],
[["PPP", 23],3],
[["KKK", 23],3]
];

I need to apply watch on arr[0][0][0] element of array.

Rendering arr[0][0][0], arr[1][0][0], arr[2][0][0] in text box using ng-model through ng-repeat for all arrays.

how to apply watch on ng-model variable as soon as i type something in text box?

I tried to apply watch on entire array arr but it didn't trigger below watch function

 $scope.$watch($scope.arr, function (newVal, oldVal) 
{ 
 $log.log(newVal);
}
);

html:

<div  ng-repeat="el in arr">
Name: <input type="text" ng-model = "el[0][0]" />
</div>
test
  • 91
  • 11

2 Answers2

0

If you only want to watch just those specific elements withing the array, you can use the Angular Scope's $watchGroup method to watch multiple expressions. Try out the example below.

angular.module("myApp", []).controller("TestCtrl", function($scope) {
  $scope.arr = [
    [
      ["TTT", 23], 3
    ],
    [
      ["PPP", 23], 3
    ],
    [
      ["KKK", 23], 3
    ]
  ];
  $scope.$watchGroup($scope.arr.map((a, i) => "arr[" + i + "][0][0]"), function(newVals, oldVals) {
    alert("Updated from " + oldVals + " to:" + newVals);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="TestCtrl">
    <div ng-repeat="el in arr">
      Name:
      <input type="text" ng-model="el[0][0]" />
    </div>
  </div>
</body>
10100111001
  • 1,832
  • 1
  • 11
  • 7
  • Thanks a lot for your help but i think the Danny's suggestion is the right reason and as well as right solution for my problem – test Aug 08 '16 at 20:42
0

It seems the issue lies in the fact that a new scope is being generated for each iteration of ng-repeat. To get around this, you can attach a separate controller for each iteration, like explained here.

The simplest way I can think of to get around this without multiple controllers is to utilize the ng-change directive, like so:

JS:

$scope.getChanged = function(newValue) {
  alert('getChanged(), new value: ' + newValue);
}

HTML:

<input type="text" ng-model="a[0][0]" ng-change="getChanged(a[0][0])" />

Here's a fiddle showing it in action.

Community
  • 1
  • 1
Danny Buonocore
  • 3,731
  • 3
  • 24
  • 46