firebolt_ash
firebolt_ash

Reputation: 1324

limitTo not working in ng-repeat in AngularJs

I am working out some code for some application. I want to limit the messages in the chat

this.limitM = -10;
$scope.msgsCount = //contains the number of messages


<button ng-if="msgsCount > -main.limitM" 
ng-click="main.limitM=-10+main.limitM">Load More</button>

<li class="singleMessage clearfix" 
    ng-repeat="msg in chat.msgs | limitTo:main.limitM" 
    ng-class="::{myMessage: msg.senderName != chat.name}">

<img class="profileImage" alt="::{{chat.name}}" width="40px">
    <p ng-bind-html="parseMsg(msg)"></p>
</li>

This is not limiting the messages, all the messages appear. Can anyone help ?

Upvotes: 4

Views: 14781

Answers (3)

Kutyel
Kutyel

Reputation: 9084

Why don't you try this:

$scope.limitM = 10; // This is your scope's limit

<button ng-click="limitM = 20">Load More</button>

<li ng-repeat="msg in chat.msgs | limitTo: limitM">{{msg}}</li>

It should work, according to the documentation.

EDIT

Check this jsfiddle to see a working example of what you try to accomplish.

Upvotes: 2

Andrii
Andrii

Reputation: 329

First you have to define all necessary variables to make it work.
Example of your controller:

$scope.limit = 3;
$scope.expand = function(limit) { 
  $scope.limit += limit;
}
$scope.chat = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];

And view:

 <button ng-if="chat.length > limit" ng-click="expand(limit)">Load More</button>
 <li ng-repeat="msg in chat | limitTo : limit" >{{ msg }}</li>

Here is a simple plunk, that does what you need.

Upvotes: 5

Syed Suhail Ahmed
Syed Suhail Ahmed

Reputation: 695

The reason why your list is not limited is because main.limitM is undefined.

I believe you are calling this.limitM = -10; inside the controller. Views cannot see the limitM variable. They only have access to variables defined on $scope.

Change this.limitM to $scope.limitM and main.limitM to limitM

Upvotes: 3

Related Questions