AngularJS中每个列表项的按钮点击计数

时间:2017-03-27 11:25:03

标签: angularjs

我有一个列表,我想分别获得每个项目的按钮点击次数。 我创建了一个示例example但是增加了所有项目。请帮忙。一个重要的事情是,JSON没有'count'键。

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 个答案:

答案 0 :(得分:2)

通过将数组修改为对象数组

,可以实现此目的
var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0} ,{"name":"three",count:0} ,{"name":"four",count:0}]}

现在像这样修改html

 <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>

然后将obj作为参数传递给function并增加该对象的计数

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

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

Demo

答案 1 :(得分:1)

试试这个

<!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) {
		// body...


		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>