6

我用 ng-repeat 生成了一个列表,其中每个项目都有一个计数变量。在我有一个链接的列表项中,我想在单击它时增加计数。

我不知道用 Angular-JS 的方式解决这个问题。

普朗克

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>

  <script>
    function increment() {

    }

  </script>
</head>

<body>
  <div ng-init="items = [
  {name:'fruit', count:4},
  {name:'car', count:1},
  {name:'dog', count:2}
  ]">
    <ul>
      <li ng-repeat="item in items">
        <span>Count:</span>
        <span>{{item.count}}</span>
        <a onclick="increment();">Increment</a>
      </li>
    </ul>
  </div>
</body>

使用 JQuery,我会为 span 分配一个唯一的 id,使用一些计数器变量,将此 id 传递给增量,找到 html 对象并更新。但我很好奇 Angular 的做法。

4

4 回答 4

8

您可以ng-click像这样操作每一行的数据模型:

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

<a ng-click="increment(item);">Increment</a>

确保你把控制器这样包装<body ng-controller="ctrl">

DEMO

于 2013-08-21T14:58:54.373 回答
6
<a ng-click="item.count = item.count + 1">Increment</a>
于 2013-08-21T15:01:15.720 回答
2

http://plnkr.co/edit/jh4UIt?p=preview

只需将 onclick 替换为 ng-click="item.count = item.count+1" 并给出 a href 属性。

<a ng-click="item.count = item.count+1" href="">Click</a>
于 2013-08-21T15:01:52.317 回答
1

这是一个解决方案

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">                                                </script>
  </head>
<body>
  <div ng-init="items = [
   {name:'fruit', count:4},
   {name:'car', count:1},
   {name:'dog', count:2}
   ]">
  <ul>
    <li ng-repeat="item in items">
     <span>Count:</span>
     <span>{{item.count}}</span>
     <a ng-click="item.count = item.count + 1">Increment</a>
    </li>
  </ul>
 </div>
 </body>
 </html>
于 2013-08-21T15:17:09.263 回答