简体   繁体   中英

How do I limit the number of objects I want to show in my ng-repeat,

This it my objects with arrays:

01-543BY: Array[1]
03-45BD23: Array[1]
03-67BS50: Array[1]
06-78FR90: Array[1]
07-467BY3: Array[1]
09-23DF76: Array[1]

Currently I have six, but I only want to show 4. This is my ng-repeat:

<div ng-repeat="(key, item) in product.productListByCategoriesShow ">

I tried <div ng-repeat="(key, item) in product.productListByCategoriesShow |limitTo: 4 "> But it seems not working. Any suggestions? Thx

I'd use this helper filter for a situation like this:

module.filter('keys', [
    function () {
        return function (object) {
            return Object.keys(object);
        }
    }
]);

And then use it like:

<div ng-repeat="key in product.productListByCategoriesShow | keys | limitTo: 4" 
     ng-init="item = product.productListByCategoriesShow[key]">
     ...
</div>

Demo:

http://plnkr.co/edit/5edaa8qScyhseB0B1Z9o?p=preview

I'd recommend sorting the keys using filter to guarantee order, as well, before calling limitTo . I'm guessing that the angular team didn't make limitTo work on objects because the order would potentially be volatile?

limitTo: {{size you want}} filter will help you in showing the number of element in list you want to display. Check this doc : https://docs.angularjs.org/api/ng/filter/limitTo

You mention that you've tried

<div ng-repeat="(key, item) in product.productListByCategoriesShow | limitTo: 4 ">

My concern would be that product.productListByCategoriesShow is the array you want to apply the filter to, but angular might be trying to apply the filter to your entire 'in' statement. Have you tried:

<div ng-repeat="(key, item) in (product.productListByCategoriesShow | limitTo: 4)">

并非最佳解决方案:

<div ng-repeat="(key, item) in product.productListByCategoriesShow" ng-if="$index < 4"></div>

为什么不限制控制器中的数组?

$scope.product.productListByCategoriesShow.length = 4

I'vs solved my problem.

limitTo, does not work for objects, only arrays and string, so what I id was to place my object into sets of arrays.

So instead of this:

01-543BY: Array[1]
03-45BD23: Array[1]
03-67BS50: Array[1]
06-78FR90: Array[1]
07-467BY3: Array[1]
09-23DF76: Array[1]

I did this: [Array[1], Array[1], Array[1], Array[1], Array[1], Array[1]] using the angular.foreach and .push(only works for arrays) it to an array.

So now my myarray | limitTo:4 works perfectly.

如果您想根据按键进行跟踪,则应像这样使用;

<div ng-repeat="item in product.productListByCategoriesShow |limitTo: 4 track by $key ">

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