AngularJS中ng-repeat / ngRepeat的全局值或缓存

时间:2013-05-22 21:03:54

标签: angularjs angularjs-ng-repeat

我正试图保留ngRepeat的全局值或某种缓存。解释起来有点复杂,所以这就是我想要做的事情。

我使用了docs:ngRepeat中的示例代码。

<body>
  <div ng-init="friends = [
    {name:'John', age:25, gender:'boy'},
    {name:'Jessie', age:30, gender:'girl'},
    {name:'Johanna', age:28, gender:'girl'},
    {name:'Joy', age:15, gender:'girl'},
    {name:'Mary', age:28, gender:'girl'},
    {name:'Peter', age:95, gender:'boy'},
    {name:'Sebastian', age:50, gender:'boy'},
    {name:'Erika', age:27, gender:'girl'},
    {name:'Patrick', age:40, gender:'boy'},
    {name:'Samantha', age:60, gender:'girl'}
  ]">
  <ul>
    <li ng-repeat="friend in friends>
      {{friend.name}} who is {{friend.age}} years old.
    </li>
  </ul>
</div>

我想总结每次重复的age值。结果应如下所示:

  • 25岁的约翰。 25 - 解释:25 + 0
  • 杰西,30岁。 55 - 说明:25 + 30
  • 约翰娜,28岁。 83 - 解释:55 + 28
  • 15岁的喜悦。 98 - 解释:83 + 15
  • ...

可以在此处找到用于实验的Plunkr http://plnkr.co/edit/VFiTOnmQ4cyqgNMDa9L4

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

<ul ng-init="ages = []">
  <li ng-repeat="friend in friends">
    {{friend.name}} who is {{friend.age}} years old. 
    {{ ages[$index] = (friend.age + ages[$index-1]) }} 
    - explanation {{friend.age }} + {{ 0 + ages[$index-1]}}
  </li>
</ul>

更新了plunker:http://plnkr.co/edit/8XCt3j?p=preview