The view does not reflect the changes made to the array in the scope after using ng-repeat to loop through

I'm working on creating a table using column names and records stored in arrays 'headers' and 'records'.

<table class="table table-striped" id="dataset">
       <thead>
            <tr>
                <th>#</th>
                <th ng-repeat="header in headers">{{ header }}</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="record in records.slice(1,11)">
                <td>{{$index + 1}}</td>
                <td ng-repeat="cell in record">{{cell}}</td>
            </tr>
        </tbody>
 </table>

Initially, both the records are set to null and they get updated once the user selects a csv file to read. After assigning values to the arrays inside the controller like this -

$scope.headers = headers;
$scope.records = records;

However, I notice that the elements are not generated in the view. In the browser console under elements, the ng-repeat directive is shown as commented out.

<table class="table table-striped" id="dataset">
       <thead>
            <tr>
                <th>#</th>
                <!-- ngRepeat: header in headers -->
            </tr>
        </thead>
        <tbody>
            <!-- ngRepeat: record in records.slice(1,11) -->
        </tbody>
</table>

I am trying to figure out what mistake I might be making.

Here's the script snippet for better understanding:

    var VizApp = angular.module('VizApp', []);

    VizApp.config(function($routeProvider){

        $routeProvider
            .when('/overview',{
                    controller : 'VizController',
                    templateUrl : 'views/overview.html'
            })
            .when('/options', {
                controller : 'VizController',
                templateUrl : 'views/options.html'
            })
            .when('/charts', {
                controller : 'VizController',
                templateUrl : 'views/charts.html'
            })
            .otherwise({redirectTo : '/overview'})
    });

    var controllers = {};
    controllers.VizController = function($scope){

        var headers = [];
        var records = [];

        var csvPath;
        var cgiPath = '/cgi-bin/cgiTest.py';

        $scope.getCsv = function(selection){
            // This function triggers when a user selects a csv file

            csvPath = 'csvs/' + selection[0].files[0].name;
            $.ajax({
                type: "GET",
                url: csvPath,
                dataType: "text",       
                success: function(data) {
                    processData(data);
                }
            });
        };

        function processData(allText) {

            var allTextLines = allText.split(/\r\n|\n/);
            headers = allTextLines[0].split(',');  

            $.each(allTextLines.slice(1,allTextLines.length), function(i,thisRecord){
                records[i] = thisRecord.split(',');
            });

            console.log("Processing completed");
            $scope.headers = headers;
            $scope.records = records; 
            // At this point, even if I do $scope.headers = ['a','b'], I still don't see two columns with headers a and b

        }
        // If I assign $scope.headers = ['a','b'] here, then I can see two columns with headers a and b
    };

    VizApp.controller(controllers);

</script>

Any guidance would be greatly appreciated.

Answer №1

Make sure to enclose your code block that updates the scope within $scope.$apply() like so:

$scope.$apply(function(){
       $scope.headers = headers;
       $scope.records = records; 
});

This is necessary because you are updating the scope within an asynchronous callback that runs in a different JavaScript turn, which AngularJS may not be aware of. For more information, refer to this post.

Alternatively, you can utilize the AngularJS $http service. In this scenario, there is no need to wrap your scope update in $scope.$apply as AngularJS handles it internally.

controllers.VizController = function($scope, $http){

        var headers = [];
        var varType = [];
        var records = [];
        var parameters = { 'xAxisVar' : '', 'yAxisVar' : '', 'sliceByVar' : '',    'chartByVar' : '', 'groups' : '', 'slices' : ''};

        var csvPath;
        var cgiPath = '/cgi-bin/cgiTest.py';


        $scope.getCsv = function(selection){
            //Triggers when user selects a CSV file input

            csvPath = 'csvs/' + selection[0].files[0].name;
            $http({method: 'GET', url: csvPath}).
            success(function(data, status, headers, config) {
                 processData(data);
            }).
            error(function(data, status, headers, config) {
            });
        };

        function processData(allText) {

            var allTextLines = allText.split(/\r\n|\n/);
            headers = allTextLines[0].split(',');  

            $.each(allTextLines.slice(1,allTextLines.length), function(i,thisRecord){
                records[i] = thisRecord.split(',');
            });

            $scope.headers = headers;
            $scope.records = records; 


        }
    };

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

Setting the z-index for data points in a scatter plot on HighCharts

Utilizing HighCharts to display a large number of points on a plot. Each point has an opacity setting and changes to red when selected. However, some points are difficult to distinguish due to overlapping. I would like the selected point to be easily visi ...

Regex Replace will only make changes to the final match found

My goal is to change the src of multiple image HTML elements in plain text (before they show up in the browser). Here's my current progress: var base = './images'; var sample = '<p><img src="1.png" alt="image-1"> ...

Errors in Intellisense detected within the latest Node Tools Express App development project

After setting up a new project with the "Basic Node.js Express 4 Application" template, I noticed some errors have already surfaced: https://i.sstatic.net/8jbYt.png Could this be a Visual Studio issue? Any pointers on resolving these errors? ...

Solutions for resolving the issue of not being able to load images when using merged-images in JavaScript

I have a base64 image here and it has already been converted. data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQSEhUTEhQWFhUXGBoaGBgYGBcXGhgXGBgYGhgbHhoZHiggGholHhgYITEhJSkrLi4uHR8zODMtNygtLisBCgoKDg0OGhAQGi0lICUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0 ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

Updating a controller variable in Angular after calling an $http service

Trying to wrap my head around the different blogs and examples regarding the proper usage of promises in Angular. It would be really helpful if someone could provide some clarity on this topic. Is it considered incorrect to use a callback passed into the ...

The AJAX in Code Igniter is throwing an error due to an undefined index 'id

I'm encountering an issue when calling a function in AJAX, as it shows the error message "Undefined index: id". Strangely, if I have only one button in the view, the function works fine. However, when there are two buttons present, the error occurs. W ...

vuejs function for modifying an existing note

Method for editing an existing note with Vue.js in a web application This particular application enables users to perform the following tasks: Create a new note View a list of all created notes Edit an existing note Delete an existing note Prog ...

Sails.JS: Harnessing the Power of Both HTTP and HTTPS

I am currently exploring the process of setting up a sails app that can handle both HTTP and HTTPS requests. To achieve this, I followed the steps outlined in the blog post available here: var fs = require('fs'); module.exports = { port: pr ...

Is there a way to verify the presence of months in a column related to departments?

Is there a way to validate whether the current row aligns with the current column month and year? If not, can it be set to 0. Let's consider the current dataset. Presenting my resultData https://pastebin.com/GHY2azzF I want to verify if this data ...

Detecting XHR objects when fetching a Backbone.js collection is essential to handling errors effectively

Within my backbone collection, I have a function called fetch_data that looks like this: fetch_data: function(data, callback) { this.fetch({ data: data, success: callback, error: function() { // detect HTTP code here } }); } I a ...

I have expanded the CSSStyleDeclaration prototype, how do I access the 'parent' property?

I have developed some custom methods for CSSStyleDeclaration and implement them like this: A_OBJECT.style.method() ; The code structure is quite simple: CSSStyleDeclaration.prototype.method = function () { x = this.left; ..... etc } Here's my que ...

Styling material-ui textfield: Tips and tricks

I've been grappling with figuring out how to customize a material-ui TextField component. <TextField id="email" label="Email" className={classes.textField} value={this.state.form_email} onChange={this.handle_change('form_e ...

Is there a way to identify when a fresh google instant page appears?

I am currently developing a browser extension that requires making a call when a new Google instant page is loaded and then modifying the results, similar to SEOQuake. One problem I encountered is that if a user pastes a link directly into the URL field a ...

Issue with AWS SDK client-S3 upload: Chrome freezes after reaching 8 GB upload limit

Whenever I try to upload a 17 GB file from my browser, Chrome crashes after reaching 8 GB due to memory exhaustion. import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage& ...

What is the best way to extract values from a string that are already mapped

Recently, I encountered this string: const string = "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVIC ...

Discovering the process of mapping transitions in MUI

I'm struggling with mapping my products in mui and placing each one in Grow. However, I keep getting this error message: "Warning: Failed prop type: Invalid prop children of type array supplied to ForwardRef(Grow), expect a single ReactElement". Can a ...

The advantages and disadvantages of utilizing various methods to visually enhance HTML elements with JavaScript

After opening one of my web projects in IntelliJ, I noticed some JavaScript hints/errors that Netbeans did not detect. The error message was: > Assigned expression type string is not assignable to type CSSStyleDeclaration This error was related to thi ...

How can I update jQuery CSS method on resize event?

Having trouble vertically centering a div inside the body? I've come up with a jQuery function that calculates the ideal margin-top value for achieving perfect vertical alignment. Here's how it works: Obtain container height, Get child height, ...

What is the best way to determine which element was clicked?

When using jquery, what method can be used to determine which object was clicked? Is there a technique to display an alert showing the type of tag that was clicked? For example, whether it was an <a href> or an <img>, etc. ...