0

I have a list and I want to get the button click count for each item separately. I have created an example example but that has increasing all items. Please help. One Important thing, the JSON doesn't have 'count' key.

var myApp = angular.module('myApp',[]);

var jsonInfo = {"count":["one", "two", "three", "four"]}

function MyCtrl($scope) {
  $scope.data =jsonInfo;

  $scope.counter = 0;
  $scope.count = function (inc) {
    $scope.counter += inc;
  };
}

2 Answers 2

2

One way you can do this by Modifying the array in to object array

var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0} ,{"name":"three",count:0} ,{"name":"four",count:0}]}

Now modify the html like this

 <li ng-repeat="list in data.count">
    <a href="#" ng-click="count(list)">
      <span>{{list.name}}</span>
      <span style="display: block;">Count: {{list.count}}</span>
    </a>
  </li>

Then pass the obj as parameter to function and increase the count of that object

function MyCtrl($scope) {
    $scope.data =jsonInfo;

    $scope.counter = 0;
    $scope.count = function (inc) {
        inc.count =  inc.count + 1
    };
}

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script type="text/javascript">
var myApp = angular.module('myApp', [])
  .controller('MyCtrl', function MyCtrl($scope) {
    var jsonInfo = [
      {
        count: 1,
        name: "one"
      },
      {
        count: 1,
        name: "two"
      },
      {
        count: 1,
        name: "three"
      },
      {
        count: 1,
        name: "four"
      }]
    $scope.data = jsonInfo;
    $scope.counter = 0;
    $scope.count = function (inc) {
      inc.count = inc.count + 1;
    };
  })
  </script>
</head>
<body>
  <div ng-controller="MyCtrl">
<ul>
  <li ng-repeat="list in data">
    <a href="#" ng-click="count(list)">
      <span>{{list.name}}</span>
      <span style="display: block;">Count: {{list.count}}</span>
    </a>
  </li>
</ul>
  </div>
</body>
</html>

2 Comments

That is the main issue. I can't add 'count' in JSON file. :(
No you cant. for that you will have to use database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.