ng-repeat not correctly restricting items in AngularJs

I'm currently working on some code for an application and I'm trying to set a limit for the messages in the chat.

this.messageLimit = -10;
$scope.messageCount = //stores the number of messages


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

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

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

Despite my efforts, the messages are not being limited and all of them continue to appear. Can anyone provide some guidance?

Answer №1

To get started, begin by defining all the necessary variables to ensure its functionality.
Take a look at this example for your controller:

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

Next, consider the view:

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

For a simple solution that meets your requirements, check out this plunk.

Answer №2

Your list is not being limited because the variable main.limitM is undefined.

You may have set this.limitM = -10; within the controller, but keep in mind that views do not have visibility to the limitM variable. Scope variables are the only ones that views can access.

To resolve this issue, update this.limitM to $scope.limitM and main.limitM to simply limitM.

Answer №3

Have you considered giving this a shot:

$scope.limitM = 10; // The limit for your scope

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

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

This method should be effective, as stated in the official documentation.

UPDATE

Take a look at this jsfiddle to see an operational demonstration of what you are trying to achieve.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on utilizing Subscribe Observable for performing lookup in Angular

I am new to Angular and seeking guidance as my approach may not be the best. Please advise me on a better solution if you have one. My goal is to display a list of records in table format, retrieved from the database where only Foreign Keys IDs are availa ...

Error code 12030: AJAX request status

When making an ajax XMLHttpRequest using the POST method, I am encountering a readyState of 4 with a status of 12030. It is known that 12030 is a Microsoft-specific state code indicating that the connection was not sustained. However, I have been unable to ...

How can you call a function in ExpressJS that is located in a different file?

I am having trouble with my UserController and database configuration file db.js. I am trying to make a function in the UserController access a function in db.js. In my UserController, I have included var db = require('../config/db'); and within ...

Utilizing ng-submit and ng-model to include a JSON object

How can I correctly insert(add) an object(nest) into a JSON using Angular? Check out the live demo here: JSbin Link I have a factory for Airports with a specific structure: angApp.factory("Airports", function () { var Airports = {}; Airports.det ...

"Step-by-step guide to building a webgrid or table to organize and display your

These are the HTML codes I have created: <table> <tr> <td><label style="text-align:left">Product Code:</label></td> <td><input type="text" id="productCode" value="" /> </td> </tr> & ...

Encountering a "Module not found" issue while attempting to utilize the Google APIs Node.js client

Attempting to incorporate the Google API Node.js client into a fresh React Web application. Here is my package.json: { "name": "onboarding", "version": "0.1.0", "private": true, "devDependencies": { "react-scripts": "0.8.4" }, "dependencie ...

What is causing the issue with passing the parameter in this angular $http.put method?

Encountering a strange issue in my angularjs application. The code snippet works perfectly fine in a factory: $http.put(apiBase + 'delete?id='+orderId); This code connects to an API endpoint to execute a PUT operation (referred to as "delete" b ...

Guide on sending a personalized email to multiple recipients using office.js

Is it possible to send individual emails when using office.js in Outlook for mail delivery? For instance, if there are 5 recipients, can the email be sent so that each recipient only sees their own email and not others'? This is unrelated to BCC fun ...

Tips for transmitting variable values through a series of objects in a collection: [{data: }]

How to pass variable values in series: [{data: }] In the code snippet below, I have the value 2,10,2,2 stored in the variable ftes. I need to pass this variable into series:[{data: }], but it doesn't seem to affect the chart. Can anyone guide me on ...

.When using element.find(), the error "undefined is not a function" is thrown in AngularJS for file upload

I am currently working on a practice project where I am trying to incorporate an image upload and save feature to a database. In order to achieve this, I have created a dialog modal along with 3 different directives for the modal elements - one for text in ...

What is the best way to stop a Vue.js state using clearInterval()?

In my Vuex code, I currently have the following: export default new Vuex.Store({ state: { intervalVar: 0 }, mutations: { SET(state, {key, value}) { state[key] = value }, }, actions: { doSo ...

Organize subarrays within an array in Mongoose

I am dealing with mongoDb data that looks like this: [{ "_id": { "$oid": "57c6699711bd6a0976cabe8a" }, "ID": "1111", "FullName": "AAA", "Category": [ { "CategoryId": { "$oid": "57c66ebedcba0f63c1ceea51" }, "_id" ...

Is there a reason why this MD Bootstrap Snippet isn't functioning properly?

When zooming out to 25% or beyond, I noticed that the toolbar unexpectedly pops open and refuses to close. How can I prevent this from happening? I asked this question yesterday but unfortunately received only downvotes :( Appreciate any help provided ...

Display a sleek Angular user interface for a calendar that seamlessly pulls events from a

I just started working with AngularJS and I am building a project that requires the use of a calendar UI to manage events from a database. I was able to successfully use the calendar by manually creating the first few events. However, when I tried to conn ...

Problem with modifying the dom within the Directive's link method - Angularjs

I have set up a custom directive like this: .directive('ogTakeATour', function() { return { restrict: 'E', replace: true, templateUrl: '../scripts/directives/TakeATourTemplate.html', scope: { content: ...

The process of altering a span label's class with JavaScript

I am currently working with an HTML element that looks like this: <dd><span class="label label-success" id="status">Production</span></dd> My goal is to update it to: <dd><span class="label label-warning" id="status"> ...

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...

Anticipate that the function will remain inactive when the screen width is less than 480 pixels

Implementing Functionality in Responsive Navigation <script> document.addEventListener('DOMContentLoaded', () => { let windowWidth = window.Width; let withinMobile = 480; let close = document.getElementById('close&ap ...

A guide on updating an item in a basic JavaScript file with Node.js

This query pertains to Workbox and Webpack, but no prior knowledge of these libraries is necessary. Background Information (Optional) Currently using the InjectManifest plugin from Workbox 4.3.1 (workbox-webpack-plugin). While this version provides the o ...

The ThreeJS WebGLRenderTarget is displaying an empty texture

Utilizing A-Frame and Three.JS, my goal is to render to a WebGLRenderTarget and generate a material based on its texture. Here's a snippet of the code: var targetPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry(2, 2), new THREE.MeshBasicMate ...