Filter Angular.js by precise values (exact match)

Check out this HTML code snippet:

  <ul ng-repeat="friend in friends | filter: { age: '2' } | orderBy: 'name' ">
   <li>{{friend.name}}</li>
  </ul>

Here is the $scope variable being used:

 $scope.friends = [
{ name: "Peter",   age: 2 },
{ name: "Pablo",   age: 55 },
{ name: "Linda",   age: 20 },
{ name: "Marta",   age: 37 },
{ name: "Othello", age: 20 },
{ name: "Markus",  age: 32 }
];

The output generated from the code is as follows:

Linda
Markus
Othello
Peter

Have questions about how the comparison works in the ng filter and how to specifically get friends with an age of 2? Look no further:

Peter

Answer №1

If you are using Angular 1.2, simply include the strict parameter (true) in the filter to ensure an exact match. Also, make sure to pass the number 2 as a number and not a string: filter:{age:2}:true

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
   $scope.friends = [
    {name: "Peter",   age: 2 },
    {name: "Pablo",   age: 55},
    {name: "Linda",   age: 20},
    {name: "Marta",   age: 37},
    {name: "Othello", age: 20},
    {name: "Markus",  age: 32}
  ]; 
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
  <ul ng-repeat="friend in friends | filter:{age:2}:true | orderBy: 'name' ">
   <li>{{friend.name}}</li>
  </ul>
</body>

Answer №2

Implemented a directive that successfully converted the model value to a number by adding the strict parameter (true) in my code.

myApp.directive('convertToNumber', [function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
      controller.$parsers.push(function(value) {
        return parseInt(value, 10);
      });

      controller.$formatters.push(function(value) {
        if (value != null) {
          return value.toString();
        }
      });      
    }
  };
}]);

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

The combination of Fabric.js, Darkroom.js, and devicePixelRatio offset creates a powerful tool

Having reached out on the Darkroom.js GitHub page with little activity, I'm turning to this platform for assistance. Despite being a great plugin overall, I've run into some issues while testing it on a Retina screen. Everything works fine on a ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

What is the purpose of using the grouping operator in this particular line of code?

While exploring the express-session npm package source code, I came across this particular line: // retrieve the session ID from the cookie var cookieId = (req.sessionID = getcookie(req, name, secrets)); Do you think it's essentially the same as this ...

The new button placed on a <div> was not initialized to trigger my greasemonkey functions

Recently, I implemented a button via GreaseMonkey: var input = document.createElement('input'); input.type = 'button'; input.value = 'Off'; input.onclick = turnTheWheelsofTime; Initially, the button functioned flawlessly whe ...

Is it possible to edit and update remote data using ng-grid?

I have implemented ng-grid and I am attempting to automatically update a single model when there are changes in the grid-table data. To achieve this, I am utilizing the edit module of ng-grid. This snippet shows my controller code: # App definition app = ...

How can you make text flash repeatedly on the screen?

I'm experimenting with creating a blinking effect for text that I want to stop after a few blinks. While the speed of the blink is correct, I am struggling to find a way to make it stop. Check out the code below: $('.blink').each(function( ...

Trigger a jQuery event when a particular element has finished loading

Is there a way to globally detect when any element (such as textarea) is displayed on the page in order to perform a specific action? The element could also be added dynamically through an AJAX request. // This code snippet is just an illustration of the ...

Hide button for the last input form to dynamically remove in jQuery

At first, I hide the remove button when there is only one form. However, if there are multiple forms and the user deletes all of them, I want the last form to remain visible and not be deleted. Can someone assist with this issue? Here is my code: <! ...

The global variable remains unchanged after the Ajax request is made

I am attempting to utilize AJAX in JavaScript to retrieve two values, use them for calculations globally, and then display the final result. Below are my code snippets. // My calculation functions will be implemented here var value1 = 0; var v ...

Guide on how to display an HTML file in Vue JS that is received from the server

I'm brand new to Vue JS and currently grappling with how to display an HTML page sent by the server. For example, let's say I have a Node router named "health" that sends an HTML file like this: res.sendFile('test.html', { root: path.d ...

using a variable in a Node.js SQL query

Hello, I am trying to send a variable in my SQL request in order to search for a value in my database. var cent = "search"; con.connect(function (err) { if (err) throw err; var sql ="SELECT * FROM cadito.activitys WHERE description like ?&qu ...

Implement the Show/Hide TinyMCE Functionality in your <textarea></textarea> Box

Information I recently added TinyMCE to my website after discovering that a website I frequently visit uses it. While their design and functionality are different, I managed to replicate their look on my own site and now want to implement a specific featu ...

Creating HTML inputs dynamically using jQuery in an ASP.NET application

I have written this JavaScript code to dynamically generate and add HTML elements within my asp.net webform: var i = 0; function addFields() { i++; var quantity = '<td class="auto-style2"><input type="text" size="3" name= ...

"By implementing an event listener, we ensure that the same action cannot be

function addEventListenerToElement(element, event, handlerFunction) { if(element.addEventListener) { element.addEventListener(event, function(){ handlerFunction(this.getAttribute("src")); }, false); } } //initialize the function addEve ...

Is it possible to remotely adjust JavaScript configurations on the client's side using JSON?

I have integrated my library into the client's website and need to set it up by providing a remote JSON file specific to the client's ID. What would be the most effective method for achieving this? Using ajax directly may not be ideal as we need ...

Error encountered during module build in Vue loader version 17.0.0 with Webpack version 5.74.0

I am encountering an issue while trying to integrate vue-loader into my SPA VUE APP. The error message I'm receiving is as follows: ERROR in ./app2.vue Module build failed (from ./node_modules/vue-loader/dist/index.js): TypeError: Cannot read prope ...

Encounter an Internal Server Error while using Laravel 5.4

I am encountering an issue while attempting to implement ajax search in my laravel project. I have included the controller and JavaScript code related to this problem below. Can you please take a look and let me know what may be causing the error? pu ...

Break down a string into an array containing a specific number of characters each

I'm currently working on a project that involves tweeting excerpts from a book daily via a small app. The book's content is stored in a text file and I need to split it into 140-character-long strings for posting. Initially, I tried using the s ...

The issue of memory leakage caused by jQuery Ajax requests

A problem has arisen on my website where memory is being leaked in both IE8 and Firefox. The Windows Process Explorer shows a continuous growth in memory usage over time. The issue arises when the page requests the "unplanned.json" URL, which is a static ...

Looking for an alternative method to compare strings in node.js without causing a call stack crash with if-else statements

I am encountering an issue with a large list of strings that need to be compared to set a variable if a match is found. I am attempting to do this within a node.js express app. However, when I try to run this comparison within an if/else statement in a f ...