"Troubleshooting: Angular ng-show not triggering correctly upon first loading of the

Utilizing Angular's ng-show directive to adjust the display of questions in a quiz and show a result upon completion, everything is functioning as intended except for the initial question. Upon loading the quiz, $scope.image is initialized as false. Surprisingly, both the div with ng-show="image" and the div with ng-show="!image" are visible. The expected behavior would be for only the div with ng-show="!image" to be displayed. Relevant code snippet provided below. Please note that I have omitted some parts of my controller and index.html for brevity:

html:

<div class="jumbotron text-center" ng-hide="quizComplete" ng-show="!image">
    <h3>{{ questions[number].ask }}</h3>
    <div class="row">
        <div ng-repeat="answer in questions[number].answers" class="choice">
            <div ng-click="recordChoice(answer.points)">
                <span class="centerer"></span>
                    <span class="centered">{{ answer.choice }}</span>
            </div>
        </div>
    </div>
</div>

<div class="jumbotron text-center" ng-hide="quizComplete" ng-show="image">
    <h3>{{ questions[number].ask }}</h3>
    <div class="row">
        <div ng-repeat="answer in questions[number].answers" class="choice">
            <div ng-click="recordChoice(answer.points)">
                <img ng-src="/img/{{ answer.img }}.jpg" alt="" class="img-responsive">
            </div>
        </div>
    </div>
</div>

<div class="jumbotron text-center" ng-show="quizComplete">
    <h2>{{ results[result].title }}</h2>
    <p>{{ results[result].details }}</p>
</div>

controller:

angular.module('NerdCtrl', []).controller('NerdController', function($scope, $routeParams) {

    $scope.questions = [{"ask": "Choose a Social Media platform:", "answers": [{"choice": "Facebook", "points": 2, "img": "Facebook"}, {"choice": "Twitter", "points": 3, "img": "Twitter"}, {"choice": "Google+", "points": 1, "img": "GooglePlus"}]}];

    $scope.results = [{title: "The Mummy", details: "You are the original..."}];


    $scope.number = 0;
    $scope.tallyMummy = 0;
    $scope.tallyFrankenstein = 0;
    $scope.tallyWolfman = 0;
    $scope.tallyJeckyll = 0;
    $scope.image = false;
    $scope.quizComplete = false;

    $scope.recordChoice = function(points) {
        if ($scope.number < 9) {
            switch(points) {
                case 1:
                    $scope.tallyMummy++;
                    break;
                case 2:
                    $scope.tallyFrankenstein++;
                    break;
                case 3:
                    $scope.tallyWolfman++;
                    break;
                case 4:
                    $scope.tallyJeckyll++;
                    break;
            }
            $scope.number++;
            if ($scope.number === 1 || $scope.number === 6 || $scope.number === 7 || $scope.number === 9) {
                $scope.image = true;
            } else {
                $scope.image = false;
            }
        } else {
            $scope.quizComplete = true;
            $scope.result = 0;
        }
    };
});

Answer №1

When using both ng-hide and ng-show in conjunction, if ng-hide evaluates to false, it is likely that both divs will be displayed. It may be helpful to test each directive individually to ensure they are functioning correctly and that the image variable has been assigned the correct value. Consider adding a wrapper div and applying ng-hide to it exclusively, preventing any conflicts between the two directives.

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

What is causing my grayscale function to only impact part of the canvas?

As a beginner programmer, I have been experimenting with creating a grayscale function in JavaScript for practice. This is the code I have come up with: <canvas width='400' height='400'></canvas> <script> var can ...

Is there a way to activate a click event on a particular child element within a parent element?

When attempting to click on a specific descendant of an element, I located the ancestor using ng-class since it lacked an id. yes = document.querySelectorAll('[ng-controller = "inventoryController"]') Having found the desired ancestor, ...

Encountering a Restangular error: "The 'then' function is not recognized" while attempting to resolve a promise

Welcome to my service. (function() { 'use strict'; angular .module('amazonScraperWebClient') .factory('dataService', dataService); /** @ngInject */ function dataService(Restangular) { Restangular.setBas ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

Reasons why Power BI embedded dashboard may not be loading

Working on a new Angular web application which is supposed to display a Power BI dashboard with app-owned data. Even though the console shows the embedToken object, the dashboard just won't load and keeps flashing the Power BI logo. No error messages ...

Is the each() method in jQuery essentially a for loop?

Experimenting with adding a serialized class to a group of objects, I attempted the following approach: jQuery('#preload img').each(function(){ jQuery('#thumbs').append('<img class="index' + index + '" src="&apos ...

Setting up an Express route for updating data

I am in the process of developing a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I am currently working on setting up an Express route for handling updates in my app... postRoutes.post('/update/:id', async(req, res)=> { cons ...

Display an Array from a PHP File in HTML Using jQuery

Here is an example of my PHP script used to retrieve and display JSON data: $get_chat = "SELECT * FROM chat WHERE u_id1='$u_id' && u_id2=2 ORDER BY data DESC"; $run_chat = $conn->query($get_chat); if ($run_chat->num_rows > 0) { ...

Tips for utilizing a variable within a variable containing HTML code

Is it possible to incorporate variables in a JavaScript function that includes HTML code? Let's consider the following example: function SetCFonts() { var Color = $('#CColor').val(); var Font = $('#CFont').val(); var S ...

Issue with loading Squarespace form when executing jQuery on Internet Explorer

One challenge I'm facing is that Squarespace builds their forms using JavaScript (YUI) and loads their code on document ready. How can I ensure that my code waits until their form is fully loaded? This issue seems to only occur in Internet Explorer. ...

Unexpected issue with PHP/Ajax/JQuery response functionality

I am experiencing an issue with my index.php file. Here is the code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="ajax.js"></script ...

The error message "Unexpected node environment at this time" occurred unexpectedly

I am currently watching a tutorial on YouTube to enhance my knowledge of Node.js and Express. To enable the use of nodemon, I made modifications to my package.json file as shown below: package.json "scripts": { "start": "if [[ $NODE_ENV == 'p ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

Issue: ui-route failing to function properly when the href attribute is utilized

I am currently working on implementing ui-route to manage the states of my app while focusing on URL navigation. My goal is to enable users to simply click on a link and be directed to the state associated with the specific URL. After following an In-Dep ...

Moment JS initialization and the utc() function

I am trying to comprehend the way Moment JS initializes its moment object. For instance, let's say I want to create a moment for the date and time: April 1, 2000, 3:25:00 AM with a UTC offset of +8 hours from UTC/GMT. To represent this in JavaScript ...

"Using the push method in JavaScript allows for the combination of arrays rather than

Looking to retrieve data from an API and store it in an array. When I assign the value directly using '=', the desired data is displayed. However, when attempting to add elements using 'push', they are added as another array. Below is ...

Steps to extract date selection from a datepicker using jQuery

I recently implemented this code snippet to utilize datepicker for displaying dates: $(document).ready(function(){ $("#txtFrom").datepicker({ numberOfMonths: 1, onSelect: function (selected) { var dt = new Date(selected); ...

The functionality of anchor links created through ajax is not operating correctly

Issue: I am encountering a problem where I have a table filled via Ajax, containing local anchors. When an anchor is clicked, it should make a section visible and automatically scroll to it. This functionality works when manually filling the table, but not ...

ng-repeat continuing to render within ng-if even when the ng-if condition is false

In my Angular application, I am using an ng-repeat directive to iterate over an array of objects. Each object in the array has a property called type and an array called contents. Depending on the type of the object, I want to display the contents array di ...

How can I properly parse a JSON file in Node.js?

Utilizing node.js, I have created a webpage (index.html) for visualizing a network graph using the vis.js library. To draw a network graph with this library, it is necessary to provide json arrays for both nodes and edges (see example). // array of nodes ...