Unable to pass a $scope variable into an Angular filter due to interpolation error

In my Angular application, I have a filter that takes a user ID and converts it into a user image URL. It does this by checking if the ID exists in an array and returning the corresponding image URL from the array passed to the filter.

The filter is functioning correctly, as the ng-repeat list displays the correct image URLs. However, I am encountering 2 errors in my console. The first error occurs on line 4 and the second error is in 'ionic.bundle.js:13380:32'

Errors:

Error: undefined is not an object (evaluating 'members.length')
Error: [$interpolate:interr] Can't interpolate: {{ participant.athlete_id | idToImage : clubMembers }} TypeError: undefined is not an object (evaluating 'members.length')


HTML:

<div ng-repeat="participant in participants | filter:{ event_id: event.id }: true track by $index">
    <img ng-src="{{ participant.athlete_id | idToImage : clubMembers }}">
</div>

Angular filter:

1 app.filter('idToImage', function () {
2   return function (id, members) {
3       var curMember = id;
4        var len = members.length - 1;
5        while(len >= 0){
6           if(curMember >= members[len].id){
7               return members[len].profile;
8           }
9           len--;
10        }
11     };
12 });

The 'clubMembers' in {{ participant.athlete_id | idToImage : clubMembers }} is an array retrieved from an external source, structured like the example below:

$scope. clubMembers = [
   {"id":1234,"profile":"https://domain.net/pictures/1.jpg"},
   {"id":12345,"profile":"https://domain.net/pictures/3.jpg"},
   {"id":12346,"profile":"https://domain.net/pictures/4.jpg"}
]

Answer №1

It seems like your filter might be missing the case where the members array is empty. If you do not account for this scenario, the length of members will cause issues and halt the code execution.

Improved Filter

app.filter('idToImage', function () {
   return function (id, members) {
       if(!members) return; // handle empty members array
       var currentMember = id;
        var maxIndex = members.length - 1; 
        while(maxIndex >= 0){
           if(currentMember >= members[maxIndex].id){
               return members[maxIndex].profile;
           }
           maxIndex--;
        }
    }
});

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

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

The HTML file seems to be having trouble connecting to the JavaScript file

I am currently working on a small, fun website project and have an HTML file along with a JavaScript file in the same directory. However, my HTML seems to be unaware of the existence of my JavaScript file. It fails to execute the function during the load e ...

Automatically scroll to the end of the data retrieved through ajax

I am currently developing a live chat website for my users and I am using ajax to fetch the chat messages. However, I am facing an issue where whenever I enter a new message, it does get added to the database and displayed, but the scroll doesn't auto ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

Exploring the capabilities of Three.js Projector and Ray components

Recently, I've been experimenting with the Projector and Ray classes for collision detection demos. My main focus has been on using the mouse to interact with objects by selecting or dragging them. While studying examples that utilize these classes, I ...

Tips for modifying jsFiddle code to function properly in a web browser

While similar questions have been asked before, I am still unable to find a solution to my specific issue. I have a functional code in jsFiddle that creates a table and allows you to select a row to color it red. Everything works perfectly fine in jsFiddle ...

Is there a way to confirm if one field value is greater than another using the Ajv JSON schema validator?

Is it feasible to receive a validation error using ajv when minPrice exceeds maxPrice? What is the recommended method of achieving this, ideally adhering to the JSON schema standard? ...

Maximizing JSON performance: Enhancing Drupal backend and optimizing IONIC Frontend

Currently, I am in the process of developing a hybrid app that combines IONIC and AngularJS, with Drupal serving as the Backend. The data is being fetched using Drupal services and returned in JSON format. My main concern lies in optimizing the speed an ...

Determine the central x and y coordinates of elements depending on the specified screen dimensions

Is it possible to determine the center position of an element at a specific screen size using jQuery? I am looking to calculate the center position of an element based on provided height and width dimensions. For instance, if I provide the screen size (1 ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

Establishing a connection between a frontend Javascript client and a backend Node.js/express server

Recently, my close friend successfully created a working client website using Javascript. Meanwhile, I have managed to get my server code up and running smoothly, extracting specific data through MySQL. We are now seeking some advice on how we can link t ...

Incorporating a dynamic URL within a script tag with AngularJs

I am currently integrating a payment gateway into my Single Page Application (SPA) using AngularJS. The issue I'm facing is that the payment gateway requires me to include a script with a specific ID for the payment process to work correctly. This i ...

Discovering the identical element within the ajax response

The following section is being targeted: var obj = $(this).parent().find('a'); // $(this) is a <UL> inside a <DIV>, but there can be multiple DIV>ULs on the page After that, I retrieve some HTML using $.ajax(). This HTML corres ...

Retrieve the index of the item that has been selected in a dropdown list

<select ng-click="getIndex($index)" size="14" ng-model="playlist.fileSelected" ng-options="saveFile for saveFile in playlist.playlist"></select> When I try to access $index, it shows up as undefined. Is there a way to retrieve the index of the ...

My code gets disrupted when I switch between ids and classes

I'm currently learning about javascript and jquery, attempting to implement various scripts. I successfully executed the following script: jQuery(document).ready(function($) { var scroll_start = 0; var startchange = $('#homepage-header' ...

Tips for adding an image into a PDF document using the jsPDF library in HTML

Due to the lack of support for utf8 characters in jspdf, I'm experimenting with replacing some characters with images before exporting to pdf. To illustrate, I've created a code sample where I insert an image into an html div and then attempt to ...

What is the best way to align the variables in this JavaScript file with the variables in Flask/Python?

I have a JavaScript file that enables dynamic drop-down menus (i.e. selecting one option affects the others). However, I hard-coded the starting variables in this file to HTML elements 'inverter_oem' and 'inverter_model_name'. Now, I ne ...

Developing an identical design and layout but utilizing a distinct domain name for the company

After being given the task of creating a website identical to an existing one with a different domain name on WordPress, I proposed using the parent HTML source code or cloning it to speed up the project. The client agreed, explaining that starting from sc ...

File is indicating a status of 200 ok, however it is not being displayed on the screen (node.js, expressjs)

I'm trying to display a video file in the browser and access it like an API on my front end. My goal is to have my front end call the video using a simple <video> tag. <video> <source ="video/randomfile.mov" type="video/mov"> < ...

Gathering information from mapped objects when they are clicked in a React application

Do you know how to retrieve genre.id when a user clicks on a Button and triggers the onClick function? Your assistance is greatly appreciated. ... return ( <div className="App"> <Header /> <div className="A ...