Reputation: 2857
I have a list with four items. Each item have a counter. When we click on the item, the count will increase. I want to reset the counter value by zero except the clicking item. This is the Demo.
var myApp = angular.module('myApp',[]);
var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0},{"name":"three",count:0} ,{"name":"four",count:0}]}
function MyCtrl($scope) {
$scope.data =jsonInfo;
$scope.count = function (inc) {
inc.count = inc.count + 1
};
}
Upvotes: 0
Views: 368
Reputation: 15292
function resetOherCount(inc) {
jsonInfo.count.map(function(oneEle) {
if (oneEle.name != inc.name) {
oneEle.count = 0
}
return oneEle;
});
}
$scope.count = function (inc) {
resetOherCount(inc);
inc.count = inc.count + 1
};
Upvotes: 0
Reputation: 68665
You can try like this. Loop over all items and check if the clicked item is the current one: increment and for others set to 0.
var myApp = angular.module('myApp',[]);
var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0},{"name":"three",count:0} ,{"name":"four",count:0}]}
function MyCtrl($scope) {
$scope.data =jsonInfo;
$scope.count = function (inc) {
jsonInfo.count.forEach((item) => {
item.count = item.name === inc.name? inc.count + 1 : 0;
});
};
}
Upvotes: 1
Reputation: 112
Try this;
function MyCtrl($scope) {
$scope.data =jsonInfo;
$scope.count = function (inc) {
for(i=0; i<jsonInfo.count.length; i++){
if(jsonInfo.count[i].name != inc.name){
jsonInfo.count[i].count = 0;
}
}
inc.count = inc.count + 1
};
}
Upvotes: 0