Franc
Franc

Reputation: 5494

Ng-repeat does not seem to create a separate Scope for each item when using array.push()

I have the following Angular View:

<div ng-repeat="item in items track by $index">
    <input ng-model="item.name"/>
</div>

In the controller, I call a service to get a Json representation of a new empty item so I can add it to the array with the following function:

$http.post("/NewItemJson").then(function (response) {
    $scope.newItem = response.data;
});

$scope.addItem = function() {
    $scope.items.push($scope.newItem);
};

But when I test the View, I see that all the new items added through the addItem() function are bound to the same scope. I can tell that because if I change one of the inputs, all the others change at the same time:

enter image description here

This is weird, because ng-repeat should create a different scope for each item. And it actually does, for all the items of the array not added with the addItem() function... but not in this case. What am I missing?

Upvotes: 1

Views: 96

Answers (1)

fikkatra
fikkatra

Reputation: 5822

You don't refresh $scope.newItem when you execute addItem(), so you're adding the same item over and over again. Try this:

$scope.addItem = function() {
    $scope.items.push(angular.copy($scope.newItem));
};

Upvotes: 2

Related Questions