计算在angularjs中单击按钮的次数

时间:2015-02-10 09:59:40

标签: html angularjs

我有5个按钮,当我点击它们时我想要它会计数。例如,我单击按钮1,计数器应增加1,当我单击按钮2时,计数器应再次增加1。所以要显示的计数器总数是2.下面是我到目前为止所做的代码,但它没有按照我的预期工作。我该怎么办?



var app = angular.module("myApp", []);
app.controller('check', function($scope) {
  
  $scope.count = function(inc){
    
    $scope.counter += inc;
  };
  
   
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="check">
 
  <button id = '1' ng-click = "count(1)" >1 </button>
  <button id = '2' ng-click = "count(1)" >2 </button>
  <button id = '3' ng-click = "count(1)" >3 </button>
  <button id = '4' ng-click = "count(1)" >4 </button>
  <button id = '5' ng-click = "count(1)" >5 </button>
  <label> Total Count : {{counter}} </label>
  </body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:4)

只需在控制器中声明计数器:

var app = angular.module("myApp", []);
app.controller('check', function ($scope) {
    $scope.counter = 0;
    $scope.count = function (inc) {
        $scope.counter += inc;
    };
});

看到这个小提琴:http://jsfiddle.net/mnotp1pc/

答案 1 :(得分:1)

您必须将$ scope.counter初始化为零

var app = angular.module("myApp", []);
app.controller('check', function($scope) {
  $scope.counter= 0;
  $scope.count = function(inc){
    
    $scope.counter += inc;
  };
  
   
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="check">
 
  <button id = '1' ng-click = "count(1)" >1 </button>
  <button id = '2' ng-click = "count(1)" >2 </button>
  <button id = '3' ng-click = "count(1)" >3 </button>
  <button id = '4' ng-click = "count(1)" >4 </button>
  <button id = '5' ng-click = "count(1)" >5 </button>
  <label> Total Count : {{counter}} </label>
  </body>

答案 2 :(得分:1)

你必须将计数器变量初始化为0, $ scope.counter = 0