The AngularJS ng-repeat filter boasts dual parameters that vary based on the scope implemented

Two different instances of the same filter are causing unexpected outputs in my ng-repeat display. One instance is scoped at the app level and defined in the module, while the other is scoped at the controller level.

Interestingly, when using the filter for the same ng-repeat display, it generates two different parameters. The app-wide filter takes all objects as a parameter, whereas the controller-scoped filter only takes each item individually. Why does this happen?

Snippet of code

Local controller-scoped filter

$scope.localFilter = function(item){
    console.log(item); //Single item

    return true;
};

//Implementation:
<div ng-repeat="post in currentStation.posts | filter:$parent.localFilter">

App-wide filter

angular.module('customFilters', [])

//Used to filter data items, often in an ng-repeat.
.filter('globalFilter', function() {

  return function(items) 
  {
    console.log(items); //multiple items

  };
});

//Implementation:
<div ng-repeat="post in currentStation.posts | globalFilter">

Answer №1

Here

"display in $parent.stationList.display | search:$parent.searchText">

You are utilizing searchText as a filtering function (argument of the searchFilter)

In this context...

<div ng-repeat="post in $parent.currentStation.posts | filterSearchText">

You are employing filterSearchText as a specialized filter.

Update

The correct format for writing a filter is as follows...

expression | filter_name:argument1:argument2:...

and you can chain filters together like so...

expression | filter_name:argument1:... | filter_name:argument1:... | ... 

In the initial example, the filter name is "filter"

In the subsequent example, the filter name is "filterSearchText"

... therefore, the first example involves using filterSearchText as an argument of the "filter" Filter. The "globalFilter" functions as a filter.

Your inquiry pertains to why the "filter" Filter processes the primary parameter in that manner... AngularJS team has designed it accordingly.

Answer №2

Your custom filter module named customFilters with the filter name currentTimeArray seems to be unused in your sample code. The filter does not seem to return any values, which goes against the intended purpose of a filter. Additionally, it attempts to call upon the $scope, even though it has not been injected.

The key distinction between using | filter : param and | customFilter lies in the fact that the former example passes a parameter to Angular's built-in filter function, while the latter implements a completely new (custom) filter.

You can view a working example in this JSFiddle: Link

It is important to note that the primary argument of the filter should be the "Data Source" (the complete list). The filter's role is to process and refine this Data Source accordingly.

Sample HTML Code:

<ul ng-controller="myCtrl">
    <li ng-repeat="row in friends | myFilter:'J': 'girl' ">{{row.name}}</li>
<ul>

Javascript App and Filter Definition:

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

myApp.filter('myFilter', function() {
        return function(items, name, gender) {                                     
            console.log("name =>",  name, "gender=> ", gender )
            return items.filter( function(i){ return i.name[0] === name && i.gender === gender } );
        }
    });

function myCtrl($scope)
{    
    $scope.friends = [
      {name:'John', age:25, gender:'boy'},
      {name:'Jessie', age:30, gender:'girl'},
      {name:'Johanna', age:28, gender:'girl'},
      {name:'Joy', age:15, gender:'girl'},
      {name:'Mary', age:28, gender:'girl'},
      {name:'Peter', age:95, gender:'boy'},
      {name:'Sebastian', age:50, gender:'boy'},
      {name:'Erika', age:27, gender:'girl'},
      {name:'Patrick', age:40, gender:'boy'},
      {name:'Samantha', age:60, gender:'girl'}
    ];
}

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

Exploring Ways to Retrieve Property Names in AngularJS JSON

I need help finding a way to use the property name as the table header in my code example below: <table> <th ng-repeat="auditorium in auditoriums"> {{ auditorium.NAME }} </th> <tbody ...

Tired of the premium content on Medium.com. How can I conceal premium posts that are aimed at a specific class within a parent element?

I have noticed that all Premium posts contain an element with the class ="svgIcon-use" <svg class="svgIcon-use" width="15" height="15" viewBox="0 0 15 15" style=""><path d="M7.438 2.324c.034-.099.090 123 0l1.2 3.53a.29.29 0 0 0 .26.19h3.884c.11 0 ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

Positioning of dropdown in Material UI select component

Unfortunately, I am encountering an issue with the Menuprops attribute and cannot seem to adjust the position of the drop-down box. Despite following the instructions from other similar queries, the desired outcome remains unachieved. My goal is to have t ...

What could be the reason for JavaScript code successfully exporting to Excel using the old office extension .xls but encountering issues when trying to export

I am currently working on exporting an HTML table to Excel using JavaScript. I have encountered an issue where it does not export to the newer version of Excel with the xlsx extension. However, it works fine and exports to older versions of Excel with the ...

The process of compressing font files (such as ArialMT.ttf) using JSZip is experiencing issues

While zipping images and HTML files works smoothly, I encountered an issue when trying to add font files for CSS. The font file is only 1kb in size, but it cannot be opened. Even after attempting to zip the font without any other files, the problem persis ...

Unable to retrieve Objects from JSON

Here is a JSON object I received: [{"model": "pricing.cashflow", "pk": 1, "fields": {"value": 4.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 2, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 3, "fiel ...

Top ways to avoid default on anchor tags: best practices for preventing this issue

Previously, excluding the criticism for not using unobtrusive JS, I typically employed anchors with inline onclick attributes for AJAX loading in the following format: <a href="http://example.com/some/specific/link.php?hello=mum" class="menu" id="m ...

Angular Link function encounters scope undefined issue

I've been struggling with this issue for some time now. Imagine I have the directive and controller setup as shown below: angular.module('LiveAPP.artist',[]) .controller('artistCtrl', ['$scope', '$http', ' ...

The AJAX request is not successful because it is encountering a ReferenceError due to attempting to assign a value to an

My attempt to trigger a modal using dynamic data from the database with an AJAX function is encountering issues. Upon clicking the button to open the modal, I encounter this error: ReferenceError: assignment to undeclared variable PostRPC in category.ph ...

Having trouble figuring out the process of mapping and showcasing data within a React application

On my backend server, I have data displaying in the following format: https://i.stack.imgur.com/f0bfN.jpg I am looking to present this data on my frontend react app. I have attempted the following so far- import {useState, useEffect} from 'react&a ...

Something is wrong with the conditional compilation in the JavaScript code

I encountered a "Conditional compilation is turned off" error in my JavaScript code. How can I resolve this issue? var <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="176264726559767a722a6765727a763976397679747f786557626739786 ...

The designated function name can be either "onButtonClick" or "onClickButton"

I am a Japanese developer working on web projects. Improving my English language skills is one of my goals. What would be the correct name for a function that indicates "when a button has been clicked"? Is it "onButtonClick"? Maybe "onClickButton"? Co ...

Users should always receive a notification, whether it be a success message or an

When I send data to my json and it returns true, a success message should be displayed. If it does not return true, an error message should be shown. The current issue is that the response should indicate whether it was successful or encountered an error. ...

Updating or removing fullCalendar events in Symfony

I'm struggling to figure out how to update or delete fullcalendar events in my Symfony project. When adding a new event, I open a modal window with a form for submitting the event and inserting it into the database. This is my working controller: $ ...

Retrieve a specific progress bar by its unique identifier and use AngularJS to dynamically update its value

How can I update the value of a specific progress bar in AngularJS based on its id? I am looking for a solution to this issue. Below are the progress bars that I have: <progressbar value="0" id="seekbar1"></progressbar> <progressbar value= ...

The application experiences crashes when the tablet is rotated, happening while in the development stage

For my web-based Android application project, I am utilizing PhoneGap and Eclipse IDE on a Windows platform. My focus is specifically on Tablet development, more precisely on the Samsung Galaxy Tab 10.1. To develop, I use Eclipse and test the app on the ...

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...

How can I update a CSS class value by utilizing AngularJS variables?

I am currently facing an issue with making my CSS values dynamic. The code I have tried is not functioning as expected. <style> .panel-primary { background-color:{{myColorPanel}} } </style> I came across a similar query on Ho ...

Re-activate video playback after 30 seconds of user inactivity (using RxJs)

My intention is to provide a brief explanation of the functionality I am looking for. Essentially, when a video is playing, I want it to pause if a user clicks on it, allowing them to do something else. Then, after 30 seconds of idle time, I need the video ...