如何在单击ng-repeat中的项时增加计数器

How do I increment a counter when clicking an item in an ng-repeat?

本文关键字:增加 计数器 单击 ng-repeat      更新时间:2023-09-26

我用ng-repeat生成了一个列表,其中每个项目都有一个计数变量。在每个列表项中我都有一个链接。

我想在点击链接时增加计数

我试了下面的方法,但它不工作。

My Controller:-

myApp.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
    var id = $stateParams.id;
    Allposts.GetAllposts(id).then(
        function (response) {
            $scope.allPosts = response.data.posts;
        });
    function ctrl($scope) {
          $scope.increment = function(item){
            item.count += 1;
          }
        }
})

和视图:-

<ion-content class="padding" lazy-scroll>
<div class="row no-padding HomeRowsList">
<div class="item itemfull" ng-repeat="post in allPosts">
        <div class="item item-body">
            <div>
                <div class="title-news">
                    <div class="title" ng-bind-html="post.content"></div>
                    <div class="countbg">عدد المرات : {{post.custom_fields.azkarno}}</div>
                    <span>{{post.count}}</span><a onclick="ctrl(post);">Increment</a>
                </div>
            </div>
        </div>
    </div>
</div>
</ion-content>

使用

$scope.increment = function(item){
    item.count += 1;
 };

代替

function ctrl($scope) {
   $scope.increment = function(item){
     item.count += 1;
    }
}

,在HTML中使用

<span>{{post.count}}</span><a data-ng-click="increment(post)">Increment</a>

代替

<span>{{post.count}}</span><a onclick="ctrl(post);">Increment</a>

应该是ng-click而不是onclick &方法名称应改为increment,而不是ctrl

也从increment方法中删除不必要的ctrl函数包装器,这根本不需要,因为无论你想从html调用什么,都应该包含在控制器的$scope中。

标记

<span>{{post.count}}</span><a ng-click="increment(post);">Increment</a>