javascript limitTo 不能在 AngularJs 的 ng-repeat 中工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28600667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:14:45  来源:igfitidea点击:

limitTo not working in ng-repeat in AngularJs

javascriptangularjs

提问by firebolt_ash

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 ?

这不限制消息,所有消息都会出现。任何人都可以帮忙吗?

回答by Andrii

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.

这是一个简单的plunk,它可以满足您的需求。

回答by Syed Suhail Ahmed

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

您的列表不受限制的原因是因为main.limitM未定义。

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.

我相信你是this.limitM = -10;在控制器内部调用。视图无法看到 limitM 变量。他们只能访问 $scope 上定义的变量。

Change this.limitMto $scope.limitMand main.limitMto limitM

更改this.limitM$scope.limitMmain.limitMlimitM

回答by Kutyel

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 jsfiddleto see a working example of what you try to accomplish.

检查此jsfiddle以查看您尝试完成的工作的示例。