user3300727
user3300727

Reputation: 101

increment and decrement of a counter for the list in angularjs

I have a list of items coming from database and the items are selected by the user and as per their selection they can add the quantity of selected item by just incrementing or decrementing the counter onClick of the signs(+,-).And i have done it this way

 <table   class="table table-hover"><tr ng-repeat="samData in sampleData">
<td >{{samData}}</td>
<td> <a ng-click="increment()">+ {{count}}</a>
  <a ng-click="decrement()" >-</a>
</td><td>

controller js:

 $scope.decrement = function() {
             $scope.count = $scope.count - 1;
            if ($scope.count < 0){
              $scope.count = 0;
           }
   };
      $scope.increment = function() {
       $scope.count = $scope.count + 1;
};

but the problem is as i click on any particular "td" all the counters gets affected which i don't want plz tel me how to associate the counter to each record and accordingly make the changes to the only clicked 'td'

Upvotes: 0

Views: 3570

Answers (3)

Malkus
Malkus

Reputation: 3726

Don't forget your $scope variable can be a JSON object. So use a value and count attribute.

You can also pass in the current value from an ng-repeat and it is used as a pointer to the record in the row.

html

<table  class="table table-hover">
    <tr ng-repeat="samData in sampleData">
        <td>{{samData.value}}</td>
        <td><a ng-click="increment(samData)">+ {{samData.count}}</a>
            <a ng-click="decrement(samData)" >-</a></td>
    </tr>
<table>

controller js

$scope.decrement = function(samData) {
     if(sameData.count > 0) {
         samData.count = samData.count - 1;
     }
}

$scope.decrement = function(samData) {
    samData.count = samData.count + 1;
}

For this implementation you would need to initialize samData.count or check for it's existence before adjusting the values

Upvotes: 0

Michael Kang
Michael Kang

Reputation: 52837

Try moving your controller inside your ng-repeat:

<table   class="table table-hover"><tr ng-repeat="samData in sampleData">
<td >{{samData}}</td>
<td ng-controller="controller"> <a ng-click="increment()">+ {{count}}</a>
  <a ng-click="decrement()" >-</a>
</td><td>

Upvotes: 2

t0mpl
t0mpl

Reputation: 5025

that's normal, you have a count for all your samdata, you need a particular one for each

try it

<td ng-init="samData.count = 0"> <a ng-click="samData.count = samData.count + 1">+      {{samData.count}}</a>
<a ng-click="samData.count = samData.count - 1" ng-if="samData.count > 0">-</a>

Upvotes: 1

Related Questions