$index, in Table, not sequential… angularjs

时光怂恿深爱的人放手 提交于 2019-12-24 08:18:06

问题


I have a table in HTML.

The rows are counted (via use of $index), and only certain rows are shown (via use of ng-show).

Problem: $index does not return the right count. The table's count should go like "1,2,3...", but it does not.

    <tbody>
        <tr ng-repeat="fruit in basket" ng-show="fruit.isJuicy == type">
            <td>{{$index + 1}}</td>
            <td>{{fruit.Name}}</td>
        </tr>
    </tbody>

Here's the JSFiddle; don't forget to click on the buttons to see the issue: http://jsfiddle.net/f6HCX/2/

What is causing this counting problem? How can it be solved?

(Could you please also comment/rate my question's description clarity, (was it easily understood?) cheers!)

Edit: This question has been answered. More info with using filters: How to use parameters within the filter in AngularJS?


回答1:


The problem is you are using ng-show to show or hide individual items. In reality, the $index is correctly counting the number of items — it's just that some are hidden, so you can't see those values.

If you look closely at your example, you'll see that the $index values match up with the original index of the items in question.

Instead, what you want to do is filter the list before it gets rendered, using the filter filter (yes, it's really confusingly named!).

Just change your tr in the html to look like:

<tr ng-repeat="fruit in basket | filter:{isJuicy:type}">

Here's a fully functional jFiddle.

What's happening:

The filter filter is used to filter a list of items against some sort of search parameters. It can take a string, which will simply search all properties of all objects to filter on, or it can take an object literal which can be used to specify which fields to search.

In this case, we've asked it to filter the list based on which items have a parameter isJuicy that matches the current value of type, which is in the scope.

Now the ng-repeat will only bother looping over the matched items, and therefore the $index will increment as expected.



来源:https://stackoverflow.com/questions/17584240/index-in-table-not-sequential-angularjs

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