BobDoleForPresident
BobDoleForPresident

Reputation: 552

AngularJs array not adding duplicates

I wrote s small bit of code that adds names to an array. The problem I am getting is that if I try add the same name more than once it will not allow me. It also will not allow me any other name after trying to add a duplicate name. Here is my Angular code

    app.controller('DirectoryController', function($scope){
$scope.name='';
$scope.names= [];


$scope.addName = function(){
    $scope.names.push($scope.name);
}

});

And here is my html

    <div ng-controller= "DirectoryController">
    <h3>Name:</h3><input type="text" ng-model='name'>
    <button ng-click = "addName()">Save</button>
    <hr/>
    <span ng-repeat="name in names">{{name}}<br/></span>
</div>

Upvotes: 3

Views: 520

Answers (1)

dustyrockpyle
dustyrockpyle

Reputation: 3184

Try changing your span to this:

<span ng-repeat="name in names track by $index">{{name}}<br/></span>

By default ng-repeat tracks items in the array by reference, and duplicate literals can have the same identity. The default behavior will cause errors when duplicates exist in your array, which will cause the behavior you see (It fails to add the duplicate, and then stops working completely).

You should probably see an error from ng-repeat in your console when it encounters duplicates.

Upvotes: 5

Related Questions