1

How do I add a new record and have angular "forget" the new item added after I click the corresponding button. The ability to add a record works and when I add the new record it display in the table I have, correctly, However my problem is that when I go to add a second record ie I remove the previous input and type something else. This results in the newly added record below to also change.

In short after I add an item to my array I want angular to forget it. How do I accomplish this.

In my controller I have this

(function () {

    var app = angular.module("mainApp");

    var ordersController = function ($scope,$filter, ordersService,customerService) {
        $scope.orders = [];


    $scope.addOrder = function (newOrder) {


            $scope.orders.push(newOrder);
        }

app.controller("ordersController", ["$scope","$filter", "ordersService","customerService", ordersController]);

}());

in my html I have this

<div><table>
            <tr>
                <td><input ng-model="item.quantity" type="text" /></td>
               <td><button type="button" ng-click="addOrder(item)">Add Line Item</button></td>
            </tr>
</table></div>
    <div>
<table>
                <tr ng-repeat="order in orders track by $index">
                    <td>
                        {{ order.quantity }}
                    </td>
              </tr>
</table>
    </div>

1 Answer 1

4

The problem might be that you are adding the newOrder object to the array while Angular keeps it's model bound to that object. Try using Angular's copy functionality like this (assuming that you are using Angular 1):

$scope.addOrder = function (newOrder) {
        var copiedOrder = angular.copy(newOrder);
        $scope.orders.push(copiedOrder);
    }

The documentation for the copy method can be found here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that worked like a charm :) I had a coworker walk by and help me out but your answer is the shorthand one which I like a lot better. For others I was pushing a pointer to the array thus everytime I updated the model everything else also updated. So in order for it to work you have to create a new object and assign each property or thanks to @J.N. you can simply call angular.copy(yourObject);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.