Angular.js: how to filter an ng-repeat by a missing key/value pair

How can I filter the ng-repeat to only display rows where all key/value pairs are present?

HTML

<div ng-app="myApp" ng-controller="oneController">
<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Country</th>
      <th>1960</th>
      <th>1970</th>
    </tr>
    <tbody>
      <tr ng-repeat="country in countries | orderBy: country.name">
        <td>{{country.name}}</td>
        <td>{{country.1960 | number}}</td>
        <td>{{country.1970 | number}}</td>
      </tr>
    </tbody>
</table>

Javascript

angular.module('myApp', []).
controller('oneController', function($scope) {
  $scope.countries = [
      {"name":"Aruba", "1960":"1567"},
     {"name":"Andorra","1960":77865,"1970":78360},
  ];
});

In this scenario, I specifically want to exclude Aruba and only show Andorra.

Complete example on CSSDeck: (excluding Aruba)

Answer №1

Creating a personalized filter is always an option:

<tr ng-repeat="city in cities | filter:customFilter | orderBy: city.name">

Here's the custom filter function:

$scope.customFilter = function(city) {
    return city.name && city.population && city.yearFounded
}

Answer №2

Discussing the idea of a custom filter further, the key point is being able to handle missing properties in objects. By iterating through all properties in all objects, a comprehensive list of every existing property on at least one object can be created:

$scope.properties = function(){
  var props = [];    
  angular.forEach($scope.countries, function(country){
    for(var prop in country){
      if(props.indexOf(prop) == -1)
        props.push(prop);
    }
  });
  return props;
};

This paves the way for creating a filtering function that cross-checks against this list:

$scope.hasAllProperties = function(item){
  var found = true;
  angular.forEach($scope.properties(), function(prop){
    if(item[prop] == undefined){
      found = false;
      return;
    }
  });
  return found;
}

Embed this filter into your HTML code:

<tr ng-repeat="country in countries | filter: hasAllProperties | orderBy: country.name">

Consider caching the master property list to optimize performance and reduce unnecessary calls to $scope.properties().

Check out the demo (Note: I removed a property from Argentina in this demonstration)

Answer №3

To address this issue, you can utilize the filter filter:

<tr ng-repeat="country in countries | filter:{name: '', 1960: '', 1970: ''} | orderBy:'name'">

Answer №4

To implement a filtering function in your controller, you can create the following code:

 $scope.filterItem = function (item){
    return item.hasOwnProperty("1970");
  };

Then, apply the filter like this:

<tr ng-repeat="country in countries | filter:filterItem | orderBy: country.name">

You can view a modified version of your code at this URL:

Answer №5

Give this a shot:

<tr ng-repeat="city in cities | orderBy: city.name">
  <label ng-show="city.population1960!=undefined && city.population1970!=undefined">
    <td>{{city.name}}</td>
    <td>{{city.population1960 | number}}</td>
    <td>{{city.population1970 | number}}</td>
  </label>
</tr>

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

Using Ajax with Laravel for Beginners

After clicking a button in my Laravel app, I want to update some data in the database using ajax without reloading the page. This is a simple ajax request where only a function in a controller needs to be invoked. I tried setting up the ajax request follo ...

Submitting a form and obtaining results without relying on jQuery

Finding information on how to accomplish this task without using jQuery has proven to be a challenge. It seems like everyone is pushing for jQuery for even the simplest tasks nowadays. Despite avoiding unnecessary use of jQuery in creating a rich experienc ...

The onsubmit function is not functioning correctly in combination with Ajax

My current implementation involves utilizing Ajax and Php for user login validation. Unfortunately, the form onsubmit function is not properly functioning. <form action="loggedin.php" onsubmit="return test()" method="post"> Below is the correspondi ...

Creating multiple CRUD components in Angular 2: which is better, using routing or a parent component

My application consists of multiple sections that act as independent CRUD components. There are two approaches that I am aware of: Utilize a parent component with ngIfs to manage the view/edit/add operations of child components Implement subrouting wit ...

What is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

javascript - Add a function to an array, iterate through, and delete once executed

I've been attempting to develop an array that stores all pending error messages appearing on the DOM using jQuery. My goal is to iterate through the array to check for any error messages to display, and then remove them after execution. However, I&ap ...

nodemon encountered an error and is currently on standby for any updates before restarting

UPDATE Upon further investigation, I have discovered that both gulp and grunt are experiencing issues in this application as well as the default installation of mean.js. This is while running the app locally on a Mac. Interestingly, when I start either app ...

Updating Elements in an Array Using JavaScript is Not Functioning as Expected

In my Angular application, I have included some lines of TypeScript code which involve Boolean variables in the constructor and an array of objects. Each object in this array contains input variables. selftest: boolean; failed: boolean; locoStateItem ...

Guide to combining an object with an array object in Vue.js

After receiving an API response's data, [{id: 1, name:"Test 1"},{id: 2, name:"Test 2"}] I am working on my component .vue file. ... created() { const request = axios.get("***api_url***").then(response => { ...

Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this: { "fields": [ { "key": "name", "label": "name", & ...

Tips for adding and removing active class with navbar links using JavaScriptonclick

I need help with toggling the "li-active" class on my navigation bar links. Currently, when I click on a link, the "li-active" class is transferred from the previous link to the newly clicked link instead of removing it first. Can someone please assist me ...

The debate between classes and data attributes in terms of auto field initialization

A Brief Background In the realm of javascript/jQuery, I've crafted a method that traverses through various fields and configures them based on their type - be it dropdowns, autocomplete, or text fields... The motivation behind this is my personalize ...

The module 'react/lib/React' could not be located within the file 'ReactTestUtils.js'

Setting up unit-tests for a React Native project using ReactTestUtils is causing an issue with npm test. The error message I receive is: Cannot find module 'react/lib/React' from 'ReactTestUtils.js' I suspect that my dependencies are ...

How can I ensure a successful redirect to react-router root path after saving to MongoDB in Express?

As a newcomer to React and react-router, I may be making some rookie mistakes in my project. Currently, I am constructing a web application with React and react-router as the frontend server, paired with Express and MongoDB for the backend. To communicate ...

Are iFrames being utilized for third-party applications?

I am looking to create a web application that can be extended by other developers with their own applications. Would using iFrames, similar to how Facebook does it, be the best approach? Is this considered a good practice in web development? Are there a ...

Compatibility of image maps with browsers and the usage of imagemapster

Currently, I am utilizing ImageMapster to make adjustments to an image map while hovering. However, I am facing challenges with both the image map itself and the ImageMapster plugin. The issues I am encountering are: 1) Despite specifying a height and wid ...

Codeigniter dilemma: Unable to upload images using Summernote

Summernote has been successfully integrated into my website (which is built using Codeigniter). Text editing functions work perfectly fine, however, I'm facing an issue with image uploads. When uploading images, Summernote reads them as base64. This ...

Using node.js with express to send data stored in a variable to the browser instead of displaying it in the

I'm currently getting the hang of node.js. It's pretty straightforward to use res.send and output some basic "hello world" text, but how can I pass variables to the browser instead of just to the console? Here is a snippet of code: var Tester = ...

Infinite scrolling with a dynamic background

Hi there, I am working on my website and trying to create a smooth transition between sections similar to the one demonstrated here:. The challenge I'm facing is that the backgrounds of my sections cannot be fixed; they need to have background-attachm ...

What could be the reason for rowsAffected not returning an integer value?

Currently, I am working on executing the SQLite statement in an iOS application. To verify the count of affected records, I have implemented success and error callback methods. Upon receiving the results, although the variables are correctly defined, I en ...