Encountering difficulties receiving notifications for changes in a list when utilizing an input field within ng-repeat directly. However, I am able to modify values and receive notifications from $watchCollection.
To illustrate:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.js">
</script>
</head>
<body>
<section ng-app="myApp" ng-controller = "TestController">
<button ng-click = "pushToList()">Add number to list.</button>
<button ng-click = "changeFirstElement()">Change first element.</button>
<textarea ng-model = "log"></textarea>
<ul>
<li ng-repeat="item in list track by $index">
<input ng-model="item"> Value: <span ng-bind="item"></span>
</li>
</ul>
</section>
<script>
angular.module("myApp", [])
.controller("TestController", function($scope){
$scope.log = '';
$scope.list = $scope.list = [1];
$scope.pushToList = function() {
$scope.list.push(Math.random());
}
$scope.changeFirstElement = function() {
$scope.list[0] = Math.random();
}
$scope.$watchCollection(
'list',
function(currentValue, oldValue) {
$scope.log += [
'Current value:',
currentValue.toString(),
'Old value:',
oldValue ? oldValue.toString() : '',
'-----',
'',
].join('\n')
}
)
});
</script>
</body>
</html>
$watchCollection successfully recognizes changes made through $scope.list[0] = Math.random();
. However, modifications via the input fields are overlooked or not detected by $watchCollection. Why is this? Is there an alternative approach?
While I understand that using a deep $watch could be a solution, I am interested in achieving this with $watchCollection for better performance. (Refer to this question for more details).
EDIT:
For a live demonstration, visit the Plunkr page.
Clicking "Add number to list" triggers $watchCollection to detect changes and update the textarea with the current array content. Similarly, changing the first number by clicking "Change first element" prompts $watchCollection to acknowledge the change and update the textarea. However, altering the values using input fields generated by ng-repeat does not produce the expected behavior. It seems that $watchCollection fails to recognize these changes and thus does not update the textarea as anticipated.