在AngularJS,什么是过滤基于奇数或偶数$ index属性数组的正确方法?奇数、偶数、数组、属性

2023-09-13 04:09:07 作者:拔剑斩情丝

我想根据偶数和奇数 $指数属性过滤一个数组,我想在另一个div添加奇数元素在一个单独的分区,甚至元素,我可以这样做很容易在JavaScript或jQuery的,但我想知道要实现AngularJS相同的正确方法。

I want to filter an array based on even and odd $index property and I want to add odd elements in a separate div and even elements in another div, I could easily do this in JavaScript or jQuery, but I wanted to know the correct way to implement the same in AngularJS.

这是我迄今所做的:

<div ng-app> 
    <div ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
        <div class="row" ng-repeat="name in names">
            <div class="col-xs-6" ng-show="(($index + 1)%2) == 0">{{name}}</div>
            <div class="col-xs-6" >{{name}}</div>
        </div>    
    </div>
</div>

它显示发生在第一种情况下奇数元素的空白空间,当我加入奇前pression的第二个div,在第二个DIV元素消失,并出现在第一个div。这里是捣鼓以同样的问题。

请指教。

编辑:

我已经得到了我想要的,我的主阵列分成奇数和偶数阵列两种不同的阵列;这个 小提琴 可能是谁在未来对同样的问题绊倒有用的人。

I have got what I wanted, I split the main array into two different arrays odd and even array; this fiddle may be useful for people who stumble upon the same issue in the future.

推荐答案

我想你将会有一些麻烦你要找的事,由于路 NG-重复的作品。它产生的每次循环新范围。所以,你会通过每次循环结束了两个div,一个可见的和一个隐藏。

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:

在你的第一种情况,循环显示两个div并显示了一格之间交替。在显示只有一格一排,这可以理解看起来像一个空白在第二列中插入。

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.

在第二种情况下,示出了第一个div和第二个之间的纳克重复循环交替。如果没有一些CSS样式以示区别,它看起来很像股利。你可以把它加入了风格,如文本信息来的div之一。

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.

我希望解释这是怎么回事幕后,但更好的问题是......什么是你想用两个div来完成?

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?

更新:因为它看起来像你的目标是把该数组和泵出来成2列布局,你也许可以用你的行格和你的2列的div做掉。相反,尝试重复单6宽度列格。它会处理的行包你每隔一列。如果你想区分的div你可以使用奇数和偶数的造型为@Blackhole指出。我有一个例子小提琴设置这里,可能是使用的。

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.