I have problem as in the topic. Using $parent in ng-model didn't help. What I am trying to achieve is 2 clickable buttons to increase and decrease quantity field value by one and display summary (sum of each price*quantity) on the bottom of site.
var app = angular.module("mainApp", []);
app.controller("mainCtrl", function ($scope) {
$scope.list1 = [
{ "uniqueId": "1", "name": "cat1" },
{ "uniqueId": "2", "name": "cat2" }
];
$scope.list2 = [
{ "uniqueId": "1", "name": "prod1", "price": "10" },
{ "uniqueId": "2", "name": "prod2", "price": "20" },
{ "uniqueId": "3", "name": "prod3", "price": "30" }
];
// this one below doesn't work at all
// $scope.quantity[1] = 1;
$scope.inc = inc;
function inc(id) {
console.log(id); //works fine
// increase of exact quantity
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp">
<div ng-controller="mainCtrl">
<table ng-repeat="l1 in list1">
<tr>
<td>
{{l1.name}}
</td>
</tr>
<tr ng-repeat="l2 in list2">
<td>name: {{l2.name}},</td>
<td>price: {{l2.price}},</td>
<td>quantity wanted: <input ng-model="quantity[l2.uniqueId]"><button ng-click="inc(l2.uniqueId)" type="button">+</button></td>
</tr>
</table>
{{quantity}}<!-- sum of all quantities * prices -->
</div>
<div>
Keep in mind that there is mulitple way to solve this kind of problem, here is the grand line I see to do it and an example for each step:
Store your quantity somewhere and initialise it, for example in your product object, example in your controller:
{ "uniqueId": "1", "name": "prod1", "price": "10", quantity : 1 },
Create a function to increase and an other to decrease the quantity of a product by his id, example in your controller:
function increaseQuantity(id){ // Get your product in the list with a loop // If the product exists // Increase his quantity } function decreaseQuantity(id){ // Get your product in the list with a loop // If the product exists // Decrease his quantity } $scope.increaseQuantity = increaseQuantity; $scope.decreaseQuantity = decreaseQuantity;
Call the right methods in your buttons, example in your view:
<td> quantity wanted: {{l2.quantity}} <button ng-click="increaseQuantity(l2.uniqueId)" type="button">+</button> <button ng-click="decreaseQuantity(l2.uniqueId)" type="button">-</button> </td>