ng-repeat count filter not refreshing multiple times

Looking at a list with filters attached, I am trying to count the items and show a message if there are no items...

<li ng-repeat="item in items = (items | sortWithTab:tab | filter:search")>
    {{ item.name }}
</li>
<div ng-if="items.length === 0">No items</div>

The 'items' set includes a tab field with a name, along with buttons to filter based on that name which updates the $scope.tab.

To display the number of items in the list, I use items.length, which works fine. However, when I go back to a tab I previously clicked on, it doesn't update. Can anyone explain why?

See the example below:

var app = angular.module('App', []);

app.controller('SampleCtrl', ['$scope',
      function($scope) {
        
        $scope.tab = 'all';
        
        $scope.changeTab = function(tab)
        {
           $scope.tab = tab;          
        }

        $scope.items = [
          {name: 'One', tab: 'live'},
          {name: 'Two', tab: 'today'},
          {name: 'Three', tab: 'today'},
          {name: 'Four', tab: 'today'},
          {name: 'Five', tab: 'live'},
          {name: 'Six', tab: 'today'},
          {name: 'Seven', tab: 'today'},
          {name: 'Eight', tab: 'live'}
        ];

      }]);

app.filter('sortWithTab', function() {
    
  return function(list, tab) {
    
    var filtered;
    var i;

    if (tab == 'all') {
      
      return list;
      
    } else if (tab == 'today') {
      
      filtered = [];
      for (i = 0; i < list.length; i++) {
        if(list[i].tab == 'today')
          filtered.push(list[i]);
      }
      return filtered;
      
    } else if (tab == 'live') {
      
      filtered = [];
      for (i = 0; i < list.length; i++) {
        if(list[i].tab == 'live')
          filtered.push(list[i]);
      }
      return filtered;
      
    } else {
      
      return list;
      
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="App" ng-controller="SampleCtrl">
  
  <a ng-click="changeTab('all')">All</a>
  <a ng-click="changeTab('today')">Today</a>
  <a ng-click="changeTab('live')">Live</a>
  
  <ul>
    <li ng-repeat="item in items = (items | sortWithTab:tab)">
      {{ item.name }}
    </li>
    Total: {{ items.length }}
  </ul>
</div>

Answer №1

Edit

 <li ng-repeat="item in items = (items | sortWithTab:tab)">

to

<li ng-repeat="item in filtered = (items | sortWithTab:tab)">

var app = angular.module('App', []);

app.controller('SampleCtrl', ['$scope',
  function($scope) {

    $scope.tab = 'all';

    $scope.changeTab = function(tab) {
      $scope.tab = tab;
    }

    $scope.items = [{
      name: 'One',
      tab: 'live'
    }, {
      name: 'Two',
      tab: 'today'
    }, {
      name: 'Three',
      tab: 'today'
    }, {
      name: 'Four',
      tab: 'today'
    }, {
      name: 'Five',
      tab: 'live'
    }, {
      name: 'Six',
      tab: 'today'
    }, {
      name: 'Seven',
      tab: 'today'
    }, {
      name: 'Eight',
      tab: 'live'
    }];

  }
]);

app.filter('sortWithTab', function() {

  return function(list, tab) {

    var filtered;
    var i;

    if (tab == 'all') {

      return list;

    } else if (tab == 'today') {

      filtered = [];
      for (i = 0; i < list.length; i++) {
        if (list[i].tab == 'today')
          filtered.push(list[i]);
      }
      return filtered;

    } else if (tab == 'live') {

      filtered = [];
      for (i = 0; i < list.length; i++) {
        if (list[i].tab == 'live')
          filtered.push(list[i]);
      }
      return filtered;

    } else {

      return list;

    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="App" ng-controller="SampleCtrl">

  <a ng-click="changeTab('all')">All</a> |
  <a ng-click="changeTab('today')">Today</a> |
  <a ng-click="changeTab('live')">Live</a> |
 

  <ul>
    <li ng-repeat="item in filtered = (items | sortWithTab:tab)">
      {{ item.name }}
    </li>
    
    <div ng-if="filtered.length === 0">No items</div>
    Total: {{ filtered.length }}
  </ul>
</div>

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

What's the best way to manage endless routing options in express.js?

After reviewing the topic of handling routes in Express.js on Stack Overflow, I came across the following example : var express = require("express"); var app = express(); app.get("/", function(request, response) { response.send(&quo ...

Steps for adding hover color to a div with linear gradient border

My current challenge involves adding a hover color to a specific div, but I'm facing obstacles due to the gradient background that was implemented to achieve border-radius functionality. This task is being carried out within a React Component using c ...

Implementing route prefix in a combination of express and react deployment

I'm currently facing a challenge while trying to deploy a react app that utilizes router functionality with express. The react app is expected to be accessible via the /dashboard route. At first glance, everything seems to be working smoothly on the ...

Printing the object name in CreateJS can be achieved by accessing the name property

var stage = new createjs.Stage("demoCanvas"); console.log(stage.constructor.name);//prints a <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script> <script src="https://code.createjs.com/createjs-2015.11.26.mi ...

The navigation buttons on the Bootstrap carousel will only respond to keyboard commands after the arrow on the

Is there a way to change the default behavior of the bootstrap carousel to allow keyboard navigation without having to click the arrows on the screen first? In my modal, I have a carousel that I want users to be able to navigate using the keyboard arrows ...

It is not possible to display JSON data that has been injected using a service within the amchart directive's datapro

I have incorporated amcharts into my custom directive. Now, I need to retrieve the dataProvider for this AmChart from the output of the $http.get service using web services. Despite my efforts, I am encountering difficulties in dynamically assigning the r ...

Tips for setting a value from an AJAX-created element into a concealed form field

There is a div that contains a button. When the button is clicked, a form appears. The div's id is then assigned to a hidden field within the form. This functionality works for the divs that are present on the page when it initially loads, but it does ...

Finding the tiniest match within a regex pattern

Looking for a way to match the fourth element in this expression: var string = [a][1] [b][2] [c][3] [d .-][] [e][4] The element we're trying to target is [d .-][]. This specific element can contain any character within the first set of brackets, whi ...

Creating a Modal in React without the need for a button to trigger it

I am working on implementing a model using the React Material UI library to display information on the landing page when a user logs in. However, I am facing an issue with closing the modal once it appears despite using a timeout trigger. const[post,setP ...

Tips for capturing text input from a Quill rich text editor div

My attempt to retrieve the content entered in Quill editor's editor div using jQuery codes is not proving successful. Although it works for other text inputs, it fails to do so for the editor div. Below is a demonstration of the issue: $(function() ...

Switching players every two turns in a JavaScript AngularJS game

I have implemented an AngularJS score keeping game where players switch every two turns. The code works for one round, but I want to create a loop that keeps switching players. Check out my code below: app.controller('EventController', function( ...

DOM not getting updated by ng-repeat when dynamically inserting elements

Utilizing jsonForm to create a dynamic form using 3 different JSON schemas. Each form submission triggers the display of the next form until all 3 forms are filled in. The data from all 3 forms is then combined into one JSON object, which is sent back and ...

What is the best way to maintain the CSS3 animation state following ng-animate?

Attempting to alter the state of a div using ng-animate along with CSS3 transitions. The animations are functioning well with this particular CSS, except for the issue where the div loses its size and color once the animation is completed. .fade-hide, .f ...

Unlawful use of the return statement

Can you identify the issue with this code? The browser reports: "Uncaught SyntaxError: Illegal return statement" I'm looking for an explanation in this format: 1 2 3fool 4 5bar 6fool 7 8 9bar... let arr = []; for (i = 0; i <= 100; i++) { if ( ...

Control the access to shared resources when dealing with asynchronous functions in JavaScript

Currently, I am developing a node.js server script that will utilize a shared text list for multiple clients to access asynchronously. Clients have the ability to read, add, or update items within this shared list. static getItems(){ if (list == undef ...

Create a form in a PHP file containing a pair of buttons for selecting a specific action

Consider the following HTML code snippet: <body onload="showcontent()"> <!-- onload attribute is optional --> <div id="content"><img src="loading.gif"></div> <!-- exclude img tag if not using onload --> < ...

Preventing cross-site scripting attacks with the help of dynamic pre elements

An expert recommended that the user content, replyContent, be surrounded by a <pre> tag to prevent XSS attacks. However, why is it commonly believed that this code effectively prevents XSS? I attempted to inject </pre><script>alert("XSS" ...

How do I incorporate an external template in Mustache.js?

Welcome, I am a beginner in using Mustache.js. Below is the template and JS code that I have: var template = $('#pageTpl').html(); var html = Mustache.to_html(template, data); $('#sampleArea').html(html); Here is the template ...

There was a problem establishing a WebSocket connection to 'ws://127.0.0.1:2000/'. The attempt failed with the following error: net::ERR_CONNECTION_REFUSED

I have integrated websocket functionality using a repository found at https://github.com/kishor10d/CodeIgniter-Ratchet-Websocket After successfully testing the websocket on my local environment, I encountered issues when uploading the files to the live se ...

What are the steps to effectively populate a mongoose schema?

In my application, I have a model for people: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PersonSchema = new Schema({ name: String, cars: [{ type: Schema.types.ObjectId, ref: 'Cars' }] }); ...