Navigating through Switch cases and If Statements with multiple arguments can be complex for beginners in the world of JavaScript

Hi there, I have a specific case that I'm struggling to find a solution for. I am using Angular with a Firebase back-end to retrieve true or false values from a variable called ref. The variable contains 4 properties with either true or false values -

{yesterdayAm: false, yesterdayPm: false, todayAm: false, todayPm: false}
.

Despite getting the expected results when running the code simply, I'm having difficulty understanding how to handle these values using if or switch expressions on the Angular/Javascript side. Can someone assist me in returning the correct values?

Let's start with the view:

<div class="col-xs-6 ">
<div class="dexbowl"><img ng-src="{{ isFed('yesterdayAm') }}"/></div>
</div>

<div class="col-xs-6">
<div class="dexbowl"><img ng-src="{{ isFed('yesterdayPm') }}"/></div>
</div>

<div class="col-xs-5 col-xs-offset-1">
<div class="dexbowl"><img ng-click="feed('todayAm')" ng-src="{{ isFed('todayAm') }}"/></div>
</div>

<div class="col-xs-5">
<div class="dexbowl"><img ng-click="feed('todayPm')" ng-src="{{ isFed('todayPm') }}"/></div>
</div>

I am attempting to feed a dog by clicking a button. Different functions like isFed('[dayAm/Pm]') are triggered by the ng-src of the img tags and return image files depicting their states. These states are defined in the $scope:

    var blueFilled = 'images/dexterbluefilled.svg';
    var satBlueFilled = 'images/SATdexterbluefilled.svg'; /* not used yet */
    var blueEmpty = 'images/dexterblueempty.svg';
    var satBlueEmpty = 'images/SATdexterblueempty.svg'; /*not used yet */

The above function in the $scope returns the image paths according to the server state:

if (Fed.getInitState(when)) {
        return blueFilled;          
    } else {
        return blueEmpty;
};

You might be wondering about the Fed.getInitState(when) function which takes arguments like

todayAm/todayPm/yesterdayAm/yesterdayPm
. This function comes from a service or factory named Fed, responsible for fetching data from Firebase.

getInitState: function(when) {
            var value = ref[when];
                return value;
            },

The object ref includes the following properties:

{yesterdayAm: false, yesterdayPm: false, todayAm: false, todayPm: false}

Here lies the problem: While everything works fine up until now, I'm struggling to incorporate two additional image paths: satBlueEmpty and satBlueFilled.

I aim to display only the "sat" image paths for the properties yesterdayAm and yesterdayPm. I have tried using an if statement within the $scope to direct the blueEmpty and blueFilled images to todayAm and todayPm, while assigning the sat path variables to yesterdayAm and yesterdayPm.

Despite experimenting with switch and nested if statements, I haven't been able to achieve the desired results. As a newcomer to Javascript and Angular, this issue has left me stuck on my first full app project. Would appreciate any guidance on updating the values being returned from the Fed service in this scenario.

*edit

A nested if function was attempted but without success:

    $scope.isFed = function(when, which) {} 
        if (Fed.getInitState(when)) {   
            if (which === sat) {
                    return satBlueFilled;
                } else {
                    return blueFilled;          
            } else {
                if (which === notSat);
                    return satBlueFilled;
                } else {
                    return satBlueEmpty;
                }
            }
        };

*edit 2

Following @Steve Lang's suggestion, I am exploring creating a switch statement inside Fed.getInitState to return values 1,2,3, or 4 to the controller function $scope.isFed. Here's what I have so far:

getInitState: function(when) {          
                var trueOrFalse = ref[when];
                console.log('when: ' + when + ' ' + 'value: ' + value);
                switch (trueOrFalse) {
                    case 'todayAm':
                        return 1;
                    case 'todayPm':
                        return 2;
                    case 'yesterdayAm':
                        return 3;
                    case 'yesterdayPm':
                        return 4;
                }       
            },

Can I use an & operator in the cases to determine the value equal to when? It seems like an if statement nested within a switch may be necessary...

Answer №1

RetrieveInitialState() has the capability to provide more than a boolean value. For instance, if RetrieveInitialState() returns a number between 1 and 4, you can define it like so:

$scope.isState = function(when) {
    switch (RetrieveInitialState(when)) {
        case 1:
            return blueFill;
        case 2:
            return blueEmpty;
        case 3:
            return saturatedBlueFill;
        case 4:
            return saturatedBlueEmpty;
    }
};

Note based on feedback

You have the option to utilize getInitState() in its original form:

getInitState: function(when) {
    var value = reference[when];
    return value;
}

However, ensure that the reference object is structured similarly to this:

{yesterdayAM: 1, yesterdayPM: 2, todayAM: 3, todayPM: 4} 

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

After updating the state, the Next.js axios call experiences a delay before executing the desired action

I am currently working on a NextJS project that relies on Axios for handling API calls. Within this project, there is a loading state implemented to show a loading spinner when making these API calls. However, I have encountered an issue where after click ...

What is the best way to alphabetically arrange an array of names in a JavaScript.map?

I am attempting to alphabetically sort an array of first names using JavaScript map function. Additionally, I aim to remove the "undefined" row from the final results: function contacts_callback(obj) { var contactinfo = obj.contacts .filter( ...

The function within the React component is failing to produce the expected output

After importing two types of images (IMG and IMG2), I wanted to display IMG when the viewport width is less than 600px, and IMG2 when it's equal to or greater than 600px. I created a function to determine the viewport width and return the respective i ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

NodeJS and ExpressJS fail to redirect to the main landing page

I am currently developing a shopping cart application using nodejs/expressjs. I have encountered an issue with redirecting back to the homepage ('/') after the user submits their credentials during sign up. Despite my search for relevant articles ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

Exploring jQuery's selection techniques involving filtering and excluding elements

How can I select all elements with the class .Tag that are not equal to the element passed to the function? Here is my current attempt: $("a.tag").filter(":visible").not("\"[id='" + aTagID + "']\"").each( function place(index, ele ...

React.js: Passing an array as a property to an element results in the transformation of the array into an object

I'm trying to understand why passing an array as a prop to another element results in it getting transformed into an object with the array as its value. I need help understanding if this is a common JavaScript 'quirk' or specific to React an ...

Navigate to a refreshed version of the page with varying parameters using React Navigation

Currently, I am utilizing React Navigation for navigating between different pages within my app. One of the pages is the Profile page which displays a user info card along with their posts. Within this Profile component, I have integrated the Post componen ...

Styling Material UI height in select elements (React)

Currently, I am developing a react application that utilizes Material Dashboard. I am encountering an issue with the height of a Select (drop-down list) component. See image here On the right side of my app, there is a standard input field and I would li ...

Navigating JSON data to retrieve a specific property in AngularJS using a select form

Struggling with AngularJS and JSON. I have a form.html view where users can select their province. I have a Province JSON file for the select tag, but when storing in MySQL, I need the province Id. I tried using ng-value="province.id" in the option tag but ...

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

What is the process for assigning values once the Google Charts program has completed its drawing?

It might sound strange, but I have a piece of code here: let globalResult = []; let defaultData = ["None", 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200]; $(document).ready(() => { // add a listener to the textbox $('#in ...

Issue with Webpack throwing 'window undefined' persists despite using the 'use client' configuration in React/Next.js

I've been using Typescript 5, React 18, and Next.js 14 as my tech stack, and I keep encountering similar errors with various libraries. One of the errors I often face is ReferenceError: window is not defined. This error originates from a third-party ...

Enhance user interactivity by incorporating dynamic checkboxes, radio buttons, checkbox groups, and radio button groups using Ext

Hello to all the amazing folks at Stack Overflow! I've tried searching for a solution to this issue on Stack Overflow, but I couldn't find anything helpful. Here is my model: Ext.define('soru', { extend: 'Ext.data.Model' ...

Guide on enabling automatic rotation using Javascript

Recently, I came across a slider online that unfortunately did not have an autorotate feature. Despite my attempts to add an autorotate function using setTimeout and click functions, I was unsuccessful. This particular slider contains 4 buttons for each s ...

Is it possible to engage in peer-to-peer chatting using the Firebase Chat application on a web platform?

I'm currently utilizing a firebase chat application in conjunction with AngularJS. My specific need is for messages to be sent from one user to another user only, without being broadcasted to all users. Are there any methods or frameworks that allow f ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

generate a listing based on an HTTP query

Here is the code snippet from my controller : @RequestMapping("/allU") public List<Utilisateur> AllU() { return UtilisateurRepo.findAll(); } When I try to access this data in my AngularJS code like this : $scope.list=$http.ge ...

Looping through a sequence of asynchronous tasks, utilizing the async/await syntax, writing data to

I'm currently working on a script to download pdf files from a specified URL and save them to my local disk. However, I have encountered an issue where I need each file to be downloaded one at a time with a one-second delay in between (to ensure that ...