Frage

I'm trying to implement an increment/decrement function on my form for a list of products. The idea is to be able to add products to cart with live update of the cart through products quantity.

I came across this code sample from Angular docs which I think could do the trick. http://docs.angularjs.org/api/ng/directive/ngClick

What I'm expecting is when I click on product for the first time it adds product to form params then increment each time I tap on product (Another solution would be to style html5 number field though but still issue with form fields logic)

enter image description here

"order": [{"product_id": "2", "quantity": "10"}, {"product_id": "5", "quantity": "12"}]

My problem is: - I can't get form right (product_id * quantity) using formData - Increment quantity function is way off

Plunker http://plnkr.co/edit/lCZUXpTeJqGkOllXaS2t?p=preview

<form ng-submit="processForm()">
  <pre>{{ formData }}</pre>

    <ul ng-repeat="product in filtered = (products | orderBy:['name'] | filter:q)">
      <li>{{ product.name }}
         <a ng-click="count = count + 1" ng-init="count=0" ng-model="formData.products">Increment - count: {{count}}
          <input type="number" ng-model="formData.{{product.id}}" />
     </a>
   </li>
  </ul>
</form>
War es hilfreich?

Lösung

you can only set quantity by binding ng-model but you are looking to set an full object {product_id: x, quantity: y}...

so use ng-change instead of ng-model to set formData...

HTML

<input type="number" ng-model="quantity" placeholder="product_{{product.id}}" 
ng-change="changeQuantity($index, product.id, quantity)">

CONTROLLER

$scope.changeQuantity =function (index, productId, quantity) {
   $scope.formData[index] = {product_id: productId, quantity: quantity};
};

here is working PLUNKER

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top