1

我正在构建我的第一个 angular-meteor 应用程序。在 app.js 文件下方找到:

libri = new Mongo.Collection("libri");

if (Meteor.isClient) {
angular.module('bookshelf',['angular-meteor']);

angular.module('bookshelf').controller('BookListCtrl', ['$scope','$meteor',
    function($scope,$meteor){


      $scope.libri = $meteor.collection(libri)

      $scope.counter = 0;
      for(i = 0; i < libri.find().count(); i++){
      $scope.counter += 1;
      }

  }]);
 }


if (Meteor.isServer) {
 Meteor.startup(function () {

   });
   }

和 index.ng.html 文件:

<div class="container">
<table class="table" ng-controller="BookListCtrl">
  <caption>Optional table caption.</caption>
  <thead>
    <tr>
      <th>Contatore</th>
      <th>Titolo</th>
      <th>Autore</th>
      <th>Casa Editrice</th>
    </tr>
   </thead>
   <tbody ng-repeat="libro in libri">
    <tr>
      <td>{{counter}}</td>
      <td>{{libro.titolo}}</td>
      <td>{{libro.autore}}</td>
      <td>{{libro.casaEditrice}}</td>
    </tr>
   </tbody>
   </table>
  </div>

我得到下表:

在此处输入图像描述

如您所见,自动递增字段 {counter} 始终为 3。我希望表格的每一行都为 1、2、3,而不在集合中创建另一个文档字段('libri')。表格的那个单元格不是 mongo 集合的一部分。有什么建议吗?为什么我不能在 html 表中打印循环?谢谢

4

2 回答 2

1

你总是只得到数字3的原因是因为这是为视图准备的。当视图在控制器前面获取数据时,计数器的值已经是 3。

你应该做的是使用$index而不是,{{counter}}它会自动从ng-repeat迭代数组中获取索引,所以你会得到1, 2, 3....

如果你想从控制器发送数据,那么你应该用你的数组填充索引。像这样的东西:

var tempArr = [
  {name: 'a'},
  {name: 'b'},
  {name: 'c'}
]

var i = 0;

for (; i < tempArr.length; i++) {
  tempArr[i].index = i;
}

console.log('updated array', tempArr);

只需将 tempArr 替换为您的数据,它应该可以顺利运行。

您可以在此处进行测试,只需检查您的控制台。

希望这可以帮助 :)

于 2015-08-06T18:19:01.533 回答
0

使用 {{$index}} 而不是 {{counter}}。

于 2015-08-06T18:15:02.797 回答