简体   繁体   中英

ngModel reference when pushed into array

I am pushing a new order into the customer.orders array and everything works fine but it seems to reference the ngModel because if I now type something into the neworder.product model it updates the view at customer.orders.product. It seems to reset itself on refresh.

Any ideas?

Some Code:

$scope.currentCustomer.orders.push($scope.newOrder);

The newOrder form:

<form id="newOrder" ng-submit="submit()">
    <input type="month" ng-model="newOrder.date" />
    <div>
      <label ng-repeat="product in products">
        {{product}}
        <input type="number" ng-model="newOrder[product]" />
      </label>
    </div>
    <button>
        Add Order
    </button>
</form>

I display my orders:

<div ng-repeat="order in currentCustomer.orders">
      <span class="header">
        {{order.date}}
      </span>
      <span ng-repeat="product in products">     
          {{product}}: {{order[products]}} 
      </span>
</div>

What happens: 1) Enter a new order and press enter. 2) Enter a new order. 3) All orders above get updated while typing? I don't understand because the ngModel is different?

I tried angular.copy

You're using the same data object for all customer' orders. Use Angular' copy method, this way every order will have its own unique object:

$scope.currentCustomer.orders.push( angular.copy($scope.newOrder) );

Working fiddle: http://jsfiddle.net/MZnML/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM