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

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

Is it possible to delete an element from a JSON file by solely utilizing the element's ID?

I'm fairly new to JavaScript and I've tried various online solutions without success. Currently, I'm working on creating a backend for a todo list application where I aim to implement the feature to delete items from the list. Below is the ...

jQuery .click() only triggering upon page load

I've been searching all over the place and I just can't seem to find a solution to my specific situation. But here's what I'm dealing with: Instead of using inline HTML onclick, I'm trying to use jQuery click() like this $(docume ...

The candy stripes on a loading bar zebra assist in creating a unique and

I'm in the process of creating my portfolio and I'd like to incorporate unique animated loading bars, such as vertical or horizontal candy stripes, to showcase my coding skills. Can anyone suggest a specific programming language or tool that woul ...

Refreshing the browser does not load the Angular2 component and instead shows a 404 error

During my exploration of Angular 2, I developed a basic restaurant management application. Now, I am delving into more advanced techniques such as creating an app bundle, minification, and optimizing the application. The authentication component in my app ...

Executing a function without using the eval() function

I am currently working on a JavaScript code that relies heavily on the eval function. eval(myString) The value of myString is equal to myFunc(arg), and I would like to find a way to call myFunc directly instead of using eval. Unfortunately, I have no co ...

jQuery disrupts the functionality of other scripts

Let me start by saying that I have very little knowledge about scripting and HTML. Recently, I came across the following code: <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> < ...

Configure unique headers for various environments

I am looking to customize headers like "id", "env", and "name" based on different environments in my application. Each environment has a unique set of values for these headers. I am struggling to implement this effectively within my existing code logic. T ...

The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning ...

Prevent form submission with jQuery during validation process

Currently, I am working on validating a form using jQuery. My main objective now is to have the submit button disabled until all fields are correctly filled in. To achieve this, I have implemented the following approach: http://jsfiddle.net/w57hq430/ < ...

Not all dynamic content is loaded through Ajax requests on a single domain

I currently have my domain forwarded (cloaked) to The main page (index.html) utilizes Ajax for loading content. All content loads properly at the original host (moppy.co.uk/wtcdi). However, on the forwarded domain (whatthecatdragged.in), some content fai ...

What is the process for transitioning from imports with <script> tags to a module bundler system?

Currently, my project utilizes Angular without a task manager or dependency manager. All libraries are stored in the repository and included using <script> tags such as <script src="libs/angular/angular.min.js"></script>. In an effort to ...

While executing a for loop, the variable $.ajax is found to be null in Javascript

When I click on a button with the function btn-book, there is a for loop inside it that fetches data from Ajax. Despite knowing that the data holds values, I constantly receive null. Below is the code snippet for the onclick event: $('#mapContainer&a ...

The integration of a Bootstrap modal within the side bar's rendering

Struggling with a modal appearing inside my side div and can't find any solutions in the bootstrap5 documentation or online forums. https://i.stack.imgur.com/gHsBi.png I just want the modal to display centered on the page with the background fade ef ...

Show or hide a div through two variables that toggle between different states

It's possible that I'm not fully awake, so missing the obvious is a possibility. However, I have 2 variables that determine whether a div has a specific class or not. The class functions more like a toggle; so the following conditions should tri ...

What is the best way to incorporate Bootstrap's datepicker into a website?

I'm currently working on an AngularJS application. Here is the code I have: <directive date="date" date-format="YYYY-MM-DD" > <input ng-model="Date" type="text"/> </directive> Is there a way to integrate an Angu ...

Creating an infinite loop animation using GSAP in React results in a jarring interruption instead of a smooth and seamless transition

I'm currently developing a React project where I am aiming to implement an infinite loop animation using GSAP. The concept involves animating a series of elements from the bottom left corner to the top right corner. The idea is for the animation to sm ...

Tips for utilizing onsubmit following an ajax validation check

How can I implement the onsubmit method after an ajax check? The current onsubmit function is not working. $(document).ready(function(){ $("#p_code").change(function(){ $("#message").html("<img src='ajax_loader.gif' width='26 ...

Discovering the current state's name with AngularJS

I am trying to access the current state name in my run() function using $state.current.name, but it seems to be returning an empty string. $rootScope.$on('$stateChangeStart', function (event, next) { var json = (function ...

JavaScript code to retrieve an image from an <img> tag's source URL that only allows a single request and is tainted due to cross-origin restrictions

I have an image displayed in the HTML DOM. https://i.stack.imgur.com/oRgvF.png This particular image (the one with a green border) is contained within an img tag and has a URL as its source. I attempted to fetch this image using the fetch method, but enc ...