-1

I have this html that binds the $scope.comments array to an unordered list;

<div ng-app="" ng-controller="commentController">
    <ul>
        <li ng-repeat="c in comments">
            {{ c }}
        </li>
    </ul>
<div>

Then this script to initialise and add more items to the list;

<script>
    function commentController($scope){
        $scope.comments = ['Hi There.'];
        $scope.addComment = function(){
            $scope.comments.push($scope.newcomment);
            $scope.newcomment='';
        };
    };   
</script>

This works fine until i attempt to add a duplicate item. Debugging shows me that Javascript does push the duplicate item to the array, but angular databinding no longer updates the list.

Any idea why, or what I am doing wrong?

srayner
  • 1,799
  • 4
  • 23
  • 39

2 Answers2

2

use this code:

<div ng-app="" ng-controller="commentController">
    <ul>
        <li ng-repeat="c in comments track by $index">
            {{ c }}
        </li>
    </ul>
<div>

track by $index track the array element by index not by value. see this in detai

Mukund Kumar
  • 21,413
  • 18
  • 59
  • 79
1

you need to track by index instead of values, so in ng-repeat editthis line

ng-repeat="c in comments track by $index"
A.B
  • 20,110
  • 3
  • 37
  • 71