Increment counter in item generated with ng-repeat

All we need is an easy explanation of the problem, so here it is.

I generated a list with ng-repeat, where each item has a count variable. In the listitems I have a link, I want to increment the count when I click it.

I don’t have a clue to solve this in Angular-JS way.

Plunker

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>

  <script>
    function increment() {

    }

  </script>
</head>

<body>
  <div ng-init="items = [
  {name:'fruit', count:4},
  {name:'car', count:1},
  {name:'dog', count:2}
  ]">
    <ul>
      <li ng-repeat="item in items">
        <span>Count:</span>
        <span>{{item.count}}</span>
        <a onclick="increment();">Increment</a>
      </li>
    </ul>
  </div>
</body>

With JQuery I would assign the span a unique id, using some counter variable, pass this id to increment, find the html object and update. But I’m curious about an Angular way to do it.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can use ng-click to manipulate the data model for each row like this:

function ctrl($scope) {
  $scope.increment = function(item){
    item.count += 1;
  }
}

<a ng-click="increment(item);">Increment</a>

Make sure you put the controller to wrap it like this <body ng-controller="ctrl">

DEMO

Method 2

<a ng-click="item.count = item.count + 1">Increment</a>

Method 3

http://plnkr.co/edit/jh4UIt?p=preview

Simply replace onclick with ng-click=”item.count = item.count+1″ and give the a href attribute.

<a ng-click="item.count = item.count+1" href="">Click</a>

Method 4

This is a solution

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">                                                </script>
  </head>
<body>
  <div ng-init="items = [
   {name:'fruit', count:4},
   {name:'car', count:1},
   {name:'dog', count:2}
   ]">
  <ul>
    <li ng-repeat="item in items">
     <span>Count:</span>
     <span>{{item.count}}</span>
     <a ng-click="item.count = item.count + 1">Increment</a>
    </li>
  </ul>
 </div>
 </body>
 </html>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply