The limitTo
filter in AngularJS is used to restrict the number of items displayed in an array or to limit the number of characters in a string. This is particularly useful when working with lists, pagination, or truncating text dynamically.
1. Syntax of the limitTo Filter
The limitTo
filter is used with the pipe (|
) operator.
{{ arrayOrString | limitTo: limitValue }}
arrayOrString
: The array or string to limit.limitValue
: The number of items (positive or negative).
Positive limitValue
→ Starts from the beginning.
Negative limitValue
→ Starts from the end.
2. Limiting the Number of Items in an Array
Example: Displaying Only the First 3 Items
<ul>
<li ng-repeat="item in items | limitTo: 3">
{{ item }}
</li>
</ul>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.items = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
});
Output
- Apple
- Banana
- Cherry
Only 3 items are displayed.
3. Displaying the Last Few Items in an Array
To show the last N
items, use a negative limit.
<ul>
<li ng-repeat="item in items | limitTo: -3">
{{ item }}
</li>
</ul>
Output
- Cherry
- Date
- Elderberry
Only the last 3 items are displayed.
4. Limiting the Number of Characters in a String
Example: Truncating a Long String
<p>{{ message | limitTo: 10 }}</p>
$scope.message = "Welcome to AngularJS filtering!";
Output
Welcome to
🔹 Only the first 10 characters are displayed.
5. Dynamic Limiting with User Input
We can use an input field to dynamically set the limit.
<input type="number" ng-model="limitValue" placeholder="Enter limit" />
<ul>
<li ng-repeat="item in items | limitTo: limitValue">
{{ item }}
</li>
</ul>
How It Works
- If the user enters
2
, only 2 items are displayed. - If they enter
-2
, the last 2 items are shown.
6. Using limitTo with Pagination
Example: Paginating a List of Items
<button ng-click="currentPage = currentPage - 1" ng-disabled="currentPage === 0">Previous</button>
<button ng-click="currentPage = currentPage + 1" ng-disabled="currentPage >= items.length/pageSize - 1">Next</button>
<ul>
<li ng-repeat="item in items | limitTo: pageSize : currentPage * pageSize">
{{ item }}
</li>
</ul>
$scope.items = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grapes"];
$scope.pageSize = 3;
$scope.currentPage = 0;
How It Works
- pageSize = 3 → Displays 3 items per page.
- currentPage * pageSize → Determines which items to show.
- Previous / Next buttons navigate between pages.
7. Performance Considerations
🔹 Using limitTo
inside ng-repeat
is efficient as it restricts the data before rendering, reducing DOM load.
🔹 For large datasets, consider pagination with limitTo to avoid performance issues.