Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment counter in item generated with ng-repeat

Tags:

angularjs

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.

like image 954
User Avatar asked Aug 21 '13 14:08

User


4 Answers

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

like image 149
zs2020 Avatar answered Nov 15 '22 08:11

zs2020


<a ng-click="item.count = item.count + 1">Increment</a>
like image 22
AlwaysALearner Avatar answered Nov 15 '22 10:11

AlwaysALearner


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>
like image 2
Drew R Avatar answered Nov 15 '22 08:11

Drew R


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>
like image 1
Rodrigo Villalba Zayas Avatar answered Nov 15 '22 10:11

Rodrigo Villalba Zayas