如何在ng-repeat中访问以前的键/值对?

时间:2015-08-27 17:37:11

标签: angularjs angularjs-ng-repeat

我的AngularJs应用程序读取具有键/值对的json文件。键/值对由使用HashMap的java程序生成。

我正在尝试使用AngularJs中的ng-repeat指令以下列方式生成HTML。

<li ng-repeat="(line, lineContents) in errorsFromLogFile">
    {{line}} - {{lineContents}} 
</li> 

我还想访问上一个(键/值)对。

通过这些stackoverflow链接How to obtain previous item in ng-repeatCompare values inside ng-repeat并尝试访问上一个密钥

{{ errorsFromLogFile[$index-1].line }} 

但它什么都没有。在这种情况下如何访问上一个键/值?

json文件看起来像这样

- errorsFromLogFile: {
     7308: "/tmp/cct7oRJm.s:2099392: Warning: .stabs: description field '11668' too big, try a different debug format",
     7309: "/tmp/cct7oRJm.s:2099393: Warning: .stabs: description field '120d3' too big, try a different debug format",
     7310: "/tmp/cct7oRJm.s:2099394: Warning: .stabs: description field '128a6' too big, try a different debug format",
     7311: "/tmp/cct7oRJm.s:2099395: Warning: .stabs: description field '13046' too big, try a different debug format",
     7312: "/tmp/cct7oRJm.s:2099396: Warning: .stabs: description field '1386c' too big, try a different debug format",
   }

1 个答案:

答案 0 :(得分:1)

您可能必须使用内部属性$$prevSibling,它提供先前的兄弟范围,在这种情况下,前一个范围由ng-repeat创建。这是因为您使用的是对象映射而不是Array。 errorsFromLogFile[$index-1]不能在对象数组中工作,因为它只是意味着您试图从数组中访问属性索引的值,即errorsFromLogFile[0], errorsFromLogFile[1]等。

{{$$prevSibling.line}} {{$$prevSibling.lineContents}} 应该有效,但不建议在范围内使用私有属性。

另一个更好的建议是将其转换为对象数组,并且只使用常规的ng-repeat迭代语法,并使用索引获取上一项。