What is the best way to determine the total number of rows that include a specific value?

Using AngularJS, I have a table that is populated with data using the ng-repeat directive. Here is an example:

http://jsfiddle.net/sso3ktz4/

I am looking for a way to determine the number of rows in the table that contain a specific value. For instance, in the provided fiddle, how can I identify the number of rows that contain the word "second"? It should return "3".

I would prefer solutions using AngularJS, but I also have JQuery at my disposal.

Thank you!

Answer №1

The updated controller code provided below includes the necessary $scope.findRowCount function:

var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);

function MyCtrl($scope) {
    $scope.items = [{
        name: 'first',
        examples: [{
            name: 'first 1'
        }, {
            name: 'first 2'
        }]
    }, {
        name: 'second',
        examples: [{
            name: 'second'
        }, {
            name: 'second'
        }]
    }];


    $scope.findRowCount=function(value){

    var count=0;
    angular.forEach($scope.items, function(item, i){
    if(item.name==value){

      count=count+1;


    }
    angular.forEach(item.examples, function(exp, j){

    if(exp.name==value){

      count=count+1;


    }

    })




    });
    console.log("count"+count);
    return count;
    }

    var result=$scope.findRowCount("second");
    console.log(result);
}

http://jsfiddle.net/p3g9vyud/

Answer №2

Here is a different approach

var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);

function MyCtrl($scope) {
    $scope.items = [{
        name: 'first',
        examples: [{
            name: 'first 1'
        }, {
            name: 'first 2'
        }]
    }, {
        name: 'second',
        examples: [{
            name: 'second'
        }, {
            name: 'second'
        }]
    }];
  //Increment sum based on the keyword
  $scope.getTotalByLabel = function(keyword)
  {
    $scope.totalSecond = 0;
    angular.forEach($scope.items, function(value, key) {
        if(value.name == keyword)
        {
          $scope.totalSecond += 1;
        }
        angular.forEach(value.examples, function(val, k) {
          if(val.name == keyword)
          {
            $scope.totalSecond += 1;
          }
        });
    });
    return $scope.totalSecond;
  }
}
th,
td {
    padding: 7px;
    text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <table border="1">
        <tbody ng:repeat="i in items">
            <tr>
                <td>{{i.name}}</td>
                <td>{{$index}}</td>
            </tr>
            <tr ng:repeat="e in i.examples">
                <td>{{e.name}}</td>
                <td>{{$index}}</td>
            </tr>
        </tbody>
    </table>
    <b>Total of second</b>: {{getTotalByLabel('second')}}
</div>
</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

Adjustable Cursor - modify size while in motion at high speeds

I've designed a unique custom cursor and I am looking to enhance its functionality by adjusting its scale dynamically during fast movements. Similar to the cursor on this website: Example.com Here is my custom cursor for reference: CodeSandBox What ...

Tips for properly handling special characters in DOM elements

I'm encountering an issue while trying to set CSS based on a condition inside quotes. This is causing a syntax error for me. Can anyone provide assistance in finding a solution? <div> <span ng-class='{\' rdng-error-rate&bsol ...

Utilizing sorting and filtering functionalities on an Angular data table

Recently, I decided to enhance my Angular skills by downloading a demo app. While working on the basics of Angular, I encountered a problem with applying a filter and sort to a data table in the app. Despite referring to some examples, I am uncertain about ...

Exploring the functionality of LINQ for sorting and searching through IEnumerable collections

I am currently new to MVC and LINQ, and I am in the process of learning how to use AngularJs and MVC for a new project that has been assigned to me. To accelerate my learning, I have turned to an online video tutorial. The tutor in the video utilizes a cod ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

resolving table refresh problem with the use of ajax, JQuery, and JSON

I have populated a set of records in HTML table format. Each row includes an anchor tag with a trash-can image at the last column. When this image is clicked, I want to delete the respective row and refresh the table with updated data. My approach involves ...

Encountering the 404 Page Not Found error upon refreshing the page while utilizing parallel routes

I'm currently developing a webapp dashboard using the latest version of Next.js 13 with app router. It features a dashboard and search bar at the top. I attempted to implement parallel routes. The @search folder contains the search bar and page.jsx wh ...

What is the outcome of XmlHttpRequest.responseText?

I am new to JavaScript and looking to explore the potential of XMLHttpRequest.responseText with a specified URL. Can someone guide me on how to efficiently test this? let url = "http://m.google.com/"; <br> let xmlHttp = new XMLHttpRequest(); <br& ...

What is the proper way to place the authorization header for a background image using the url()

I am currently working on fetching background images through a REST API. However, in order to successfully retrieve these images, I have to go through an authorization process. The token required for authorization is already present in the context where ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Steps to remove a specific child element using jQuery:

CSS: <h1><br style="clear:both;"></h1> I am currently working on a project that involves using the Wikipedia API. One issue I've run into is cleaning up the raw HTML output from Wikipedia, specifically dealing with removing a speci ...

How can JavaScript allow access to files outside of a web server environment? Could .htaccess provide a

Currently, I'm facing a challenge with my local server on Mac 10.8. I am trying to serve files such as videos and images from an external hard drive. The path for the external hard drive is HD: /Volumes/ while the web server's path is /Library/Se ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Using JSON parsing to dynamically create classes with preloaded background images

Today, I successfully deployed my browser game using MVC4 to my website for the first time. I am currently navigating through the differences between running the site off of localhost and running it from the actual website. My process involves loading all ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Issue with undefined arrays in the Angular merge sort visualization tool

I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the ...

Turn off scroll bar to create a seamless browsing experience on your website

As I work on creating the frontend for a single-page website with seamless scrolling between divs, I'm looking to eliminate mouse scrolling altogether. I understand that using overflow:hidden; can hide scroll bars, but my goal is to make the page scr ...

What is the best way to bring in a variable initialized by an IIFE from a JavaScript file into a TypeScript class?

I'm currently working towards integrating the steelseries.js library (found at https://github.com/HanSolo/SteelSeries-Canvas) into a Grafana plugin built with React. It's quite a complex task, but I'm up for the challenge. Right now, my ma ...

Creating dynamic form groups that allow for the addition and removal of forms while assigning unique identifiers and names to each input field

I am currently immersed in the development of a sophisticated CMS system. My main objective is to dynamically add and remove form inputs using JavaScript upon clicking a button, with the ultimate goal of submitting the data into a database via PHP script. ...