Search code examples
javascriptjqueryangularjsloopslimit

limitTo: not working in AngularJS


AngularJS

userData.success(function (userdataobject) {
                  $scope.catadata = userdataobject;
                $scope.quantity = 1;
            });
            userData.success(function (userdataobject) {
                  $scope.catadata1 = userdataobject;
                $scope.quantity1 = 1;
            });

AngularJS 2 different Loops code

Loop-1

 <div ng-repeat="cat in catadata | limitTo:quantity | filter: {TopCategoryID : 11}">

Loop-2

<div ng-repeat="cat1 in catadata1 | limitTo:quantity1 | filter: {TopCategoryID : 12}">

limitTo:quantity is working but limitTo:quantity1 is not working


Solution

  • TLDR: You will have to move the limitTo filter to the end:

    <div ng-repeat="cat1 in catadata1 | filter: {TopCategoryID : 12} | limitTo:quantity1">
    

    The limitTo filter will create a new array with the desired length, then your filter will be applied, consider this:

    var catadata1 = [
        {TopCategoryID: 13, ...},
        {TopCategoryID: 42, ...},
        {TopCategoryID: 12, ...},
        ...
    ];
    // When we apply the limitTo, this is what's happening:
    var limitTo = catadata1.slice(0, 1); // Keep the first item
    // And when we apply the filter we only filter on the limitTo array:
    var filter = limitTo.filter(matchItem({TopCategoryID : 12}));
    

    Another way to look at is:

    var a = [0, 1, 2]; // Initial Array
    var b = [0] // limitTo: 1
    var c = [] // filter: 2
    

    While:

    var a = [0, 1, 2]; // Initial Array
    var b = [0] // limitTo: 1
    var c = [0] // filter: 0
    

    This is what is happening in your code, just with another filter.