My controller in AngularJS is having trouble fetching the latest values of the $scope variables

In my code, I've included the relevant snippet below. The base angularJS seems to be functioning properly as the HTML document doesn't display {{}} variables but instead remains blank.

I suspect that this is due to the variables receiving a null value. When I include console.log expressions within the controller, I can see that the values are being updated correctly, but this differs when outside the controller context.

Here is the code snippet:

 <div ng-controller="rangeSort"> 
            <h3>Range Selection</h3>

            <div class="row">
                <div class="col-md-4">
                    <h5><b>Observer</b></h5>
                    <select class="form-control" ng-model="obSelection">
                        <option value="" >All</option>
                        <option ng-repeat="observer in observersS" value="{{observer}}">{{observer}}</option>
                    </select>
                </div>

                <div class="col-md-4">
                    <h5> <b>Host</b></h5>
                    <select class="form-control" ng-model="hostSelection">
                        <option value="" >All</option>
                        <option ng-repeat="host in hostsS" value="{{host}}">{{host}}</option>
                    </select>
                </div>

                <div class="col-md-4">
                    <h5> <b>Bug</b></h5>
                    <select id="chooseBug" class="form-control" ng-model="bugSelection">
                        <option value="" >All</option>
                        <option ng-repeat="bug in bugsS" value="{{bug}}" >{{bug}}</option>
                    </select>
                </div>
            </div>

            <!--div  ng-repeat="bugItem in bugsJSONList | filter: obSelection | filter: hostSelection | filter: bugSelection" > {{bugItem.bug}} on {{bugItem.host}} , observer {{bugItem.observer}} </div-->
            <div class="row">
                <div style="text-align: center; margin-bottom: 15px" ng-repeat="observer in observerKeys | filter: obSelection" > 
                    <h5><b> {{observer}}</b></h5>
                    <div class="row">
                        <div class="col-md-6" ng-repeat="host in hostKeys | filter: hostSelection" >
                            <br> <span style="text-decoration:underline"> Host {{host}} </span>
                            <div style="text-align: left" ng-repeat="bug in bugsS | filter: bugSelection" >
                                <div ng-repeat="item in JSONbugsList[observer][host][bug]">{{bug}} from {{item.start}} to {{item.end}}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <script>
                var summaryApp = angular.module('summaryApp', []);
                summaryApp.controller("rangeSort", function($scope) {
                    hosts =[], observers =[], bugs =[], JSONbugsList =[];
                    hostKeys = [], observerKeys = [], bugKeys = [];

                    bugTracker = {};


                    $.getJSON('../java_output/bug_summary.json', function (data) {
                        JSONbugsList = data;
                        var numObservers = data.numObservers;
                        var bugTracker = {};
                        for (var observer = 1; observer <= numObservers; observer++) {
                            observers.push(observer);
                            observerKeys = Object.keys(data);
                            observerKeys.splice(observerKeys.indexOf('numObservers'));
                            for (var host in data["observer" + observer]) {
                                if (hosts.indexOf(host) == -1) {
                                    hosts.push(host);
                                }
                                hostKeys = Object.keys(data["observer" + observer]);
                                for (var bug in data["observer" + observer][host]) {
                                    if (bugs.indexOf(bug) == -1) {
                                        bugs.push(bug);  
                                    }
                                    for (var i in  data["observer" + observer][host][bug]) { 
                                        bugTracker[bug] = true;
                                        var dateVar = data["observer" + observer][host][bug][i];
                                        var intoList = {"observer":observer, "host":host, "bug":bug, "start":(new Date(1000*dateVar.start)), "end":(dateVar.end==null?' the end.':(new Date(1000*dateVar.end)))} 
                                        }
                                }
                            }
                        }

                        console.log ("host keys " + hostKeys);

                        var overviewVars = ['Congestion','Highlatency','LownumOIO'];
                        var overviewSpaceVars = ['Congestion','High latency','Low numOIO'];
                        for (var i in overviewVars) {
                            console.log (overviewVars[i]);
                            $('#' + overviewVars[i] + 'Content' ).append ('<p>There are' + ((bugTracker[overviewSpaceVars[i]])?' errors in ':' no errors in ') + overviewVars[i] + '.</p>');
                            $('#' + overviewVars[i] + 'Content' ).append ('<button type=\"button\" class=\"btn\" onclick=\"displayRanges('+overviewSpaceVars[i]+')\">View Bug Ranges</button>');
                        }

                        function displayRanges (bug) {
                            $('#chooseBug').val(bug);
                        }

                        //console.log(bugsCounter);
                        for (var i = 1; i <= numObservers; i++) {
                            $('#links').append('<a href=\"#observer' + i + '\">Observer ' + i + '   </a>');
                            if (i != numObservers) {
                                $('#links').append(' - ');
                            }
                        }
                        $scope.hostsS = hosts;
                        $scope.bugsS = bugs;
                        $scope.observersS = observers;
                        $scope.JSONbugsList = JSONbugsList;
                        $scope.hostKeys = hostKeys;
                        $scope.observerKeys = observerKeys;
                        $scope.start = 'start';
                        $scope.end = 'end';
                    });


                });

            </script>

            <hr>


        </div>

Answer №1

fetchData is not a Vue method, which means it won't trigger any reactivity and your view won't update. Mixing Vue and vanilla JavaScript is discouraged for this reason. Vue provides its own set of methods to handle DOM manipulation.

To ensure reactivity, you should use Axios for data fetching instead. As a workaround, you can force an update by calling this.$forceUpdate() at the end of your code block, but it's recommended to refactor your code to utilize Vue dependencies for better performance.

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

The ng-click functionality seems to be malfunctioning when used within the controller in conjunction with ng-bind

After coding, I noticed that my ng-click function is not working. When I inspected the element, I couldn't find ng-click displayed anywhere. Can someone please help me figure out what I'm doing wrong? var app = angular.module('myApp' ...

Change the hover effects on the desktop to be more mobile-friendly

In my desktop version, I have implemented some code that enables hovering over a button to display additional information or text. How can I modify this for mobile so that nothing happens when the button is tapped on? .credit:hover .credit-text, .credit- ...

Is it possible to incorporate additional sections by utilizing map and props in the given code snippet?

I have a component named CardItems.jsx which specifically defines the appearance of a card. Then, I also have Gotocart.jsx where there is a welcome section (similar to welcoming someone to their cart) and an order section at the end (for initiating an orde ...

Is there a conventional method for implementing role-based access control for files in Angular?

I have built 4 projects in Angular that grant access to different roles. The dashboard consists of various content pages, with the initial page being the dashboard when a user logs in. The content displayed on the dashboard is determined by the logged-in ...

NodeJS: Increasing memory consumption leads to system failure due to recursive scraping

Currently, I am utilizing a GET URL API in NodeJS to extract various data by looping through the months of the year across multiple cities. For each set of parameters such as startDate, endDate, and location, I invoke a scrapeChunk() function. This functio ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...

What makes the state display potential when utilizing Redux? Also, what is the best approach to access the array within the outcome?

Upon logging the state here, I noticed a promising result. However, I am struggling to access the array inside the promise outcome. I attempted using Object.keys and map but was unsuccessful. > import React, { useEffect, useState } from 'react&apos ...

Enhance the editing capabilities of the Json data form

https://i.stack.imgur.com/YZIjb.png My goal is to enhance a form for editing json data by moving beyond the typical <textarea /> tag and making it more user-friendly. Are there any tools available that can help improve the form's usability? Add ...

Prevent unnecessary image resizing during parallax scrolling animation

Check out my demonstration where the image scaling results in the margin-top of the parallax wrapper being unable to dynamically adjust. Demonstration: http://jsfiddle.net/KsdeX/12/ .wrapper-parallax { margin-top: 150px; margin-bottom: 60px; } W ...

Updating a document using the nano module in CouchDB is not supported

I am currently utilizing the Node.js module known as nano Why is it that I am unable to update my document? I need to set crazy: true and then change it back to false. This is the code I have: var nano = require('nano')('http://localhost ...

Why does it appear that Angular is undefined in this straightforward Angular demonstration?

I'm completely new to AngularJS and I've encountered an issue. Yesterday, I ran a very simple AngularJS application that I downloaded from a tutorial and it worked perfectly. The application consists of 2 files: 1) index.htm: <!DOCTYPE htm ...

Strategies for accessing the initial portion of an AJAX response

When using ajax to call an URL with dataType HTML, the response includes two parts such as accesstoken=1&expires=452. In this scenario, only the access token is needed. Using alert(response) displays both parts. How can the access token be extracted? ...

HackerRank Challenge: Strategies for Efficiently Solving Minimum Swaps 2

In this challenge, the goal is to determine the minimum number of swaps needed to arrange an array of disordered consecutive digits in ascending order. My code successfully handles most of the tests, but I'm encountering timeout errors with four speci ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

Verify if item is currently on wishlist

Is there a way to verify if products have been added to the wishlist for logged in customers? I would like to display the result on a twig file, showing whether the product is already on the wishlist. button color=red else button color=gray In addition, ...

Gather every hyperlink and input fields without utilizing jQuery

Is there a way to target all a and form elements without relying on jQuery? My end goal is to achieve the following functionality: document.querySelectorAll('a').forEach(element => { element.addEventListener('click', () => { ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

Alerting Users Before Navigating Away from an Angular Page

I am looking to implement a feature in my app that will display a warning message when attempting to close the tab, exit the page, or reload it. However, I am facing an issue where the warning message is displayed but the page still exits before I can resp ...