In the absence of an Avatar, verify the gender from the JSON data and insert it into the image

I have created my very first app where users can upload their avatars and set their gender. If a user (in this case, a girl) does not upload an avatar, I want to check the JSON data for their gender information. Based on this gender information, I want to display the URL to the default female avatar.

Take a look at my Controller Code:

$scope.getUserImage = function (user) {
    if (user.avatar) {
        return user.avatar;
    } else {
        return '/images/icons/user-' + user.gender + '.svg';
    }
};

$scope.schueler = [
    {
        firstName: 'Sven',
        lastName: 'Wauback',
        gender: 'male',
        avatar: 'url to avatar',
        notice: 'Almost done with theory'
    },
    {
        firstName: 'Sonja',
        lastName: 'Flockenbarsch',
        gender: 'female',
        avatar: 'url to avatar',
        notice: 'Needs extra practice hours'
    },
    {
        firstName: 'Lisa',
        lastName: 'Weber',
        gender: 'female',
        avatar: '',
        notice: 'Not interested in photo submission'
    },
    {
        firstName: 'Manuel',
        lastName: 'Bürstenkrieger',
        gender: 'male',
        avatar: 'url to avatar',
        notice: 'Thinks he's the coolest'
    }
];

Now let's take a look at the View File:

<md-list-item ng-repeat="item in schueler" class="md-2-line" ng-click="null">
    <img ng-src="getUserImage(user)" class="md-avatar" alt="{{item.firstName}} {{item.lastName}}"/>
    <div class="md-list-item-text" layout="column">
        <h3>{{item.firstName}} {{item.lastName}}</h3>
        <p>{{item.notice}}</p>
    </div>
    <md-divider></md-divider>
</md-list-item>

I attempted to create a function above, but it doesn't seem to be working. As I am not familiar with JavaScript, I believe my approach is incorrect. Can someone guide me on the correct way to achieve this?

Answer №1

It appears that the incorrect value is being passed for the image source. Isn't it supposed to be getUserImage(item) instead of getUserImage(user)?

Edit: To retrieve the value, use ng-src="{{getUserImage(item)}}"

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

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

Using $scope.$on name parameter as an attribute within an AngularJS directive

My goal is to create a directive that allows me to pass in an attribute string, which will then be used as the "name" parameter when subscribing to events using $scope.$on. The process involves: An object is broadcasted using $rootScope.$broadcast, label ...

Using database entries to generate dynamic routes in express.js without the need for a server restart

I have created a custom Express instance for my KeystoneJS v5 app that serves data stored in a Postgres database with the following model: CREATE TABLE "Link" ( id integer DEFAULT PRIMARY KEY, customer text, slug text ); I've set up dyna ...

Error encountered during JSON object conversion

How can I convert the string below into an object? "{"taskStatus":"Not Started","taskFields":{"originalTransactionDate":"${datafield:feerefund:originalTranDate}","transactionPostingDate":"${datafield:feerefund:tranPostingDate}","referenceNumber":"${data ...

The CORS policy is preventing the AJAX request from functioning properly on localhost

Recently, I have been working on an Angular application that requires interaction with an API. To test it out, I set up an API on my localhost and made a request using AJAX. However, I encountered the dreaded CORS error. Despite trying various solutions fo ...

Validation of forms - Must include one particular word from a given set

I am in the process of utilizing Javascript to validate an input field with the specific formatting requirements outlined below: "WORD1,WORD2" The input must contain a comma separating two words, without any spaces. The first word (WORD1) can be any word ...

Getting Errors When Retrieving Data with Apostrophe Symbol ' in Node.js

I am currently developing a Next.js API page to extract data from a series of URLs. Interestingly, the URLs containing an apostrophe character ' fail to return any data, while those without it work perfectly fine. Surprisingly, when I execute the same ...

Guide to configuring angular-rails 4.2 with devise for user registration and authentication

Do you have any recommendations or resources related to this topic? I grasp the theory behind it, but I've also heard about JWT etc. What are the most effective methods for implementing role-based authentication/registration in a device/angular/rails ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

The Rails/Ajax function is not replacing the DIV as expected, but rather nesting a new DIV inside

Struggling to dynamically update a DIV using AJAX after a form submission. Here is the content of my partial _inline.html.erb: <div class="large-12 columns" id="inline_posts"> <% @posts.each do |post| %> <div class="row"> <div ...

How to effortlessly assign keys to values within a JSON object using Python

This is how my JSON data is structured: "docs": [ { "key": [ null, null, "some_name", "12345567", "test_name" ], "value": { ...

Is it possible to display a value conditionally based on a condition from a Json object?

I'm looking to add a new feature that displays all the movies featuring Sean Connery in a button, but I'm stuck on how to implement it. Prettier 2.7.1 --parser babel </pre> Input: import React, { useState } from "react"; import ...

What happens when Google Polymer platform is used without defining _polyfilled?

My attempt at creating a simple example using Google Polymer's platform.js is running into an error message that says: Uncaught TypeError: Cannot read property '_polyfilled' of undefined This is what I'm attempting to achieve: <cur ...

How can we enable a sitemap for web crawlers in a nodejs/express application?

Looking to enable sitemap for web crawlers in nodejs/express? I am trying to figure out where I should place my sitemap folder/files within the application flow and how to allow access for web crawlers. Currently, when visiting domain/sitemap/sitemap.xml, ...

Graph columns failing to display on Chart.js bar chart

I'm currently facing a challenge while trying to create a bar chart using HTML and JavaScript. Unfortunately, the bars are not showing up for some reason. I have included the code snippet below along with an imagehttps://i.stack.imgur.com/4H7ol.png. ...

Dynamic web elements can be easily enhanced through the use of jQuery

Upon loading a page through AJAX, I encountered the following code involving animation of a div (#1 moves it to the left and #2 moves it back): #1 $('#flipper').click(function () { $(".l-l").animate({ "left": -267 }, 600, function () { ...

socket.io initialization and finalization events

Currently, I am integrating socket.io with express 3 for my application development. I am interested in implementing loader animations that will appear when a message is incoming and disappear once the message has been received. Similar to how jQuery&apos ...

Error: The index "id" is not defined

Hey there, I have been working on fetching data from a JSON URL located at this link. However, I seem to be encountering an error that I can't quite comprehend. If anyone has any insights or solutions, I would greatly appreciate the help. Thank you in ...