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.
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
<a ng-click="item.count = item.count + 1">Increment</a>
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With