Is it possible to apply an object method for filtering an ng-repeat?

I'm still getting the hang of angular and JavaScript OOP, looking to create a reusable component in Angular that can bind all controls to an instance of a JavaScript object. One strange issue I came across is when attempting to filter a collection using a method from a JavaScript object.

The object has a method named filterVisible with this signature:

this.filterVisible = function(item) 

When trying to use ng-repeat filtered by this object method:

ng-repeat="item in item1.items | filter: item1.filterVisible"

It doesn't seem to work as expected. However, if I wrap the object method within a $scope method like this:

$scope.filterVisible1 = function(item) {
  return ($scope.item1.filterVisible(item));
}

and then update my repeat to:

ng-repeat="item in item1.items | filter: filterVisible1"

It works perfectly fine.

This situation was a bit perplexing, so I've created a plunker to demonstrate. Can someone shed light on why the filter works with the scope method but not directly with the object method?

Answer №1

Upon reviewing the document, it is evident that the http://docs.angularjs.org/api/ng.filter:filter

{{ filter_expression | filter:expression:comparator }}

One can utilize expressions with the filter, where the evaluation of properties occurs within the scope being evaluated. This differs from JavaScript, where expressions are evaluated against the global window as described in the documentation at http://docs.angularjs.org/guide/expression.

The pertinent question to ask is

item1.filterVisible is defined within the scope? vs. filterVisible1 is defined within the scope?

The string "item1.filterVisible" is evaluable by Javascript, but not a suitable expression for the $scope.$eval() method.

To ensure the functionality of your expression, execute the following in the Chrome console after selecting your element.

angular.element($0).scope().$eval(<your expression>)

Moreover, it is advisable for objects to have meaningful method names. In this instance, filterVisible may lead to confusion.

-- Edit --
It has come to light that both codes provided are indeed defined within $scope. I discovered a JS error, which can be rectified as follows.

  var _this = this;
  this.filterVisible = function(item) {
    return (Math.abs(_this.items.indexOf(item) - _this.selected_id) <= _this.limit);
  }

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 UNHANDLEDREJECTION callback was triggered prematurely during asynchronous parallel execution

Asynchronously using parallel to retrieve data from the database in parallel. Upon each task returning the data, it is stored in a local object. In index.js, the cacheService.js is called. Inside cacheService.js, data is loaded from both MySQL and MongoDB ...

Tips for maintaining a persistent login session in React Native with Firebase forever

I've been grappling with this issue for a few days now. Essentially, my aim is to have Firebase remember the user so they remain logged in after logging in once. The first block of code is the App component (I've omitted some of the irrelevant co ...

Merge a variety of arrays containing different data types

Imagine we have an array called colorArray = ['B', 'G', 'R', 'A'] and another array named array2 as Uint8Array. How can we concatenate these two arrays together? I attempted to use var newArray = colorArray.concat(a ...

There seems to be an issue with the modal display in Angular 4

When trying to create a modal sample using ng-bootstrap as shown Here, the modal does not appear when clicked, even though it exists in the DOM. https://i.sstatic.net/XxSga.png My angular core version is 4.0.0, @ng-bootstrap/ng-bootstrap version is 1.0.0- ...

Identify the credit card as either American Express or American Express Corporate

My JavaScript code can successfully detect credit card types, but I have encountered an issue. I am unable to differentiate between American Express and American Express Corporate cards. Is there a way to distinguish them or is it impossible to identify wh ...

"Function.click operates successfully when no arguments are given, but encounters issues when arguments are supplied

I had a function that was functioning correctly: $('#buttFurniture').click(onFilterCLick); However, when I decided to pass arguments to the function, it stopped working: $('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture ...

How to efficiently await multiple promises in Javascript

My Objective: Collect artist IDs Find them in the database Create new ones if needed Create an event record in the database and obtain its ID Ensure all artist IDs and event ID are gathered before proceeding Loop through combin ...

What could be the reason for the inability to generate the response using response.writeHead and response.write functions?

I recently started learning about node.js and I'm facing an issue with the code inside the if and else loop for the '/socket.html' case. Despite my efforts, I always get a 200 status code and a blank response when accessing the URL localhost ...

The hyperlink is unclickable because of the menu

The code below contains a menu on the right side with a hover effect and some content with a link. However, the link is not clickable due to the menu. .menubar{position: fixed;right:0;top: 50%;transform: translateY(-50%);-webkit-transform: translateY(-5 ...

Determine if two arrays share the same keys

Looking to compare two arrays and update them with matching keys while adding 0 for non-matching keys. For example: let obj1 = [ {"type": "Riesenslalom","total": 2862}, {"type": "Slalom", "total" ...

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...

Error alert: The function name used in the import statement is not defined

I've taken the initiative to organize my JavaScript functions into separate files based on their respective web pages (index, login, register, etc.), and then importing them all into a main JS file. This helps with code maintenance and readability, pr ...

Failure to receive a server response during the AJAX communication

I am facing an issue with my code that is making 3 requests to a server. The code successfully sends the request, but fails when receiving the response. I need help in skipping the first response and only getting the third one. phone.open("POST", '/& ...

Is it possible to retrieve the ID instead of the country name in the autocomplete feature?

I implemented Autocomplete from @Mui in my component const Profile = () => { const { register, handleSubmit, setValue, formState: { errors }, } = useForm({}); const [countries, setCountries] = useState([]); const submit = asyn ...

Transferring a variable value between functions using autocomplete and AJAX communication

I am facing difficulties with implementing autocomplete jQuery along with AJAX call. The issue arises when a user enters text in the input field, triggering an AJAX POST request to the controller which retrieves values from the database and sends them back ...

Issue encountered when utilizing Sequelize and Express for API routing

I'm struggling to troubleshoot the routing issue I'm facing. As a newcomer to Sequelize and Express routing, I would appreciate any guidance. My objective is to retrieve a JSON response from a Sequelize query when accessing the API endpoint &apo ...

The FireBase getToken function with the forceRefresh set to true has failed to perform as expected

I encountered a problem with this code snippet from Firebase when trying to run it in Angular 2 CLI. It gives an error of 'unreachable code'. How can I fix this issue and get it to work properly? firebase.auth().currentUser.getToken(/forceRefres ...

Taking steps when a number is enclosed within a span

Testing a simple code with similar action to what I want. Apologies for any language errors, hoping to be understood :-) The HTML code snippet: <div class="pagination"> <a href="#" class=""><span>1</span></a> <a href=" ...

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

Error: Attempts to access the 'avatar' property of a null value result in a TypeError

I've been attempting to showcase both an avatar and the user name, but I keep encountering this error. Despite trying to declare a user variable to troubleshoot, it's not resolving the issue. Error: Cannot read property 'avatar' of n ...