简体   繁体   中英

How to access previous key/value pair in ng-repeat?

My AngularJs app reads a json file having key/value pairs. The key/value pairs are generated by a java program using HashMap.

I am trying to generate HTML using ng-repeat directive in AngularJs in the following manner.

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

I also want to access the previous (key / value) pair.

Gone through these stackoverflow links How to obtain previous item in ng-repeat , Compare values inside ng-repeat and tried to access the previous key as

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

but it gives nothing. How to access previous key/value in this case?

The json file looks like this

- 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",
   }

You may have to use internal property $$prevSibling which gives the previous sibling scope and in this case previous scope created by ng-repeat . This is because you are using an object map and not Array. errorsFromLogFile[$index-1] will not work in array of objects because it just means that you are trying to access value of property index from the array, ie errorsFromLogFile[0], errorsFromLogFile[1] etc.

ie {{$$prevSibling.line}} and {{$$prevSibling.lineContents}} which should work, but is not advisable to use private properties on scope.

Another better suggestion is to convert it to array of objects and just have regular ng-repeat iteration syntax and get the previous item using the index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM