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

Utilizing React and Google Code to Enhance Lead Conversion Pages

I have developed a basic react application featuring a contact form. Upon submission, I aim to display the Google Code for the lead Conversion Page within the application. <!-- Google Code for Purchase Conversion Page --> <script type="text ...

Using references to pass variables in JavaScript - passing variables to an external test in Mocha

When dealing with primitive datatypes in JavaScript, passing by reference doesn't work. One common workaround is to wrap them in an object. However, what happens if a variable starts as null and then gets reassigned as an Object before being passed to ...

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

consolidating express routes in one consolidated file

I am attempting to consolidate routes into a single file using app.use app.js import express from 'express' import testRouter from 'testRouter' const app = express() app.use('/testRouter', testRouter) app.listen(3000) tes ...

React does not accept objects as valid children

Currently, I am working on developing a stopwatch using reactive js. Here is the code snippet that I have been working on: <div id="root"></div> <script src="https://unpkg.com/library/react.development.js"></script> <script sr ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

How to Embed a Javascript (jquery) Variable within a JSON Object

I have searched everywhere for a "simple answer" to this problem, but unfortunately, I cannot find a solution that aligns with my understanding of JSON and jQuery. Perhaps I am too much of a beginner in JSON to accurately formulate the right question (and ...

Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below [ { "subjectID": 1 "Chosen" : "{subjectsChosen:Python,java,Angular}" "password": "{studentpw:123456abcd}" }, { "subjectID": 2 ...

I desire to perform a specific task when there is a modification in the path using react router framework

Though I am mindful of it. props.history.listen((location, action) => { console.log("when route changes",location); }) However, I need to implement it in a slightly different way. For instance, let's cons ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

What are some tips for integrating Bluebird into Angular frameworks?

I attempted to integrate Angular with Bluebird promises: Here is the HTML code snippet: <body ng-app="HelloApp"> <div ng-controller="HomeController">{{name}} {{also}}</div> </body> The corresponding JavaScr ...

Listening for select elements that have remained unchanged

My current situation involves a select box with predetermined options. One of these options is preselected when the page loads: <select name="select" class="js-choice-select"> <option value="option-1">Option 1</option> <option ...

Customizing the default settings of a d3 funnel chart

I recently used the following link to create a funnel chart using D3: jakezatecky/d3-funnel Everything was working perfectly. However, I wanted to adjust the block heights in proportion to their weight as mentioned in the tutorial by changing the D3 defau ...

Seamless mathematical computations while navigating through Javascript

I have created a basic JavaScript calculator that works efficiently. However, after obtaining the result by pressing the "=" button, I would like the returned result to be saved for future use. The "=" button should be capable of being clicked again to ret ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

Enhancing search results with data retrieved from a jSON response

At the moment, I am using a logic to generate a list of titles. Now, I would like to include data from the response along with the code for each title in the list. const title = responseData.map(item => { return { label: item.title, val ...

Are there any alternatives to writing a multitude of 'if...elif' statements when using Python with websockets and SQL?

Currently, I am developing a websocket API to fetch real-time data from a data provider and update my database accordingly. The incoming data is in JSON format. The workflow involves sending an initial request to the server which responds with a JSON paylo ...

The specified file for import cannot be located or is unable to be read: node_modules/bootstrap/scss/functions

I am currently using core UI version 2.1.1 along with react. Upon attempting to execute npm start, I encountered the following error: (/Users/umairsaleem/Desktop/abc/abc/node_modules/css-loader??ref--6-oneOf-5-1!/Users/umairsaleem/Desktop/abc/abc/node_mo ...

Vue.js is displaying the error message "Expected Object, got Array" when the length appears as undefined

I have an app where users input style codes into a field. I want to create a popup confirmation modal that displays a message with the number of style codes provided. The code I currently have is: <template> <h4>Style Number</h4> <For ...

Utilizing jQuery to Trigger a Click Event on an Element Without a Class

What is the best way to ensure that the "click" event will only be triggered by an href element unless it does not have the "disablelink" class? Avoid processing the following: <a class="iconGear download disablelink" href="#">Download</a> P ...