简体   繁体   English

限制在AngularJs中不在ng-repeat中工作

[英]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 ? 有人可以帮忙吗?

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. 这是一个简单的插件可以满足您的需求。

The reason why your list is not limited is because main.limitM is undefined. 列表不受限制的原因是因为main.limitM未定义。

I believe you are calling this.limitM = -10; 我相信你在说this.limitM = -10; inside the controller. 在控制器内部。 Views cannot see the limitM variable. 视图无法看到limitM变量。 They only have access to variables defined on $scope. 他们只能访问$ scope上定义的变量。

Change this.limitM to $scope.limitM and main.limitM to limitM 更改this.limitM$scope.limitMmain.limitMlimitM

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. 检查这个jsfiddle以查看您尝试完成的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM