In AngularJS, what is the correct way to filter an array based on odd or even $index property?

三世轮回 提交于 2019-12-06 16:08:34

I think you're going to have some trouble with what you're looking to do, due to the way ng-repeat works. It generates a new scope for each iteration of the repeat. So you'll end up with two divs each time through the loop, one visible and one hidden.

To explain the weird behavior you've been seeing:

  • In your first case, the loop is alternating between showing two divs and showing one div. In a row that displays only one div, it understandably looks like a blank was inserted in the second column.

  • In the second case, the ng-repeat loop alternates between showing the first div and the second one. Without some CSS styling to show the difference, it looks like one div. You can make it pop by adding a style such as text-info to one of the divs.

I hope that explains what's going on behind the scenes, but the better question is... what are you trying to accomplish with the two divs?

Update: Since it looks like your goal is to take that array and pump it out into a 2-column layout, you can probably do away with your row div and your 2 column divs. Instead, try repeating a single 6-width column div. It'll handle the row wrapping for you every other column. You can use odd and even styling as @Blackhole pointed out if you want to differentiate the divs. I've got an example fiddle set up here that may be of use.

Since Angular 1.2.0-rc1, ngRepeat exposes the $odd and $even properties on the local scope. You can simply use an ngSwitch based on one of this properties:

<div ng-repeat="item in itemsList" ng-switch="$even">
    <div ng-switch-when="true">{{item}} is even</div>
    <div ng-switch-default>{{item}} is odd</div>
</div>

Notice that if you just want to change the class based on the parity, ngClassOdd and ngClassEven are available since 1.0.0:

<div ng-repeat="item in itemsList" ng-class-even="'even'" ng-class-odd="'odd'">
    {{item}}
</div>

All-in-one Fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!