angularjs populating an array using values from another array

(Still learning angularjs) I attempted to populate an array by parsing a CSV file, and it seems like I was successful as everything is correctly stored in the $scope.videos array. However, when I tried to split that array during page load using the init() function, and continue adding to it while scrolling, I encountered an error on the first attempt to push into the array variable.

TypeError: Cannot read property 'frame' of undefined
at init (MainController.js:33)
at new <anonymous> (MainController.js:45)
at Object.invoke (angular.js:4709)
at R.instance (angular.js:10234)
at m (angular.js:9147)
at g (angular.js:8510)
at angular.js:8390
at angular.js:1756
at m.$eval (angular.js:17444)
at m.$apply (angular.js:17544)




mvcApp.factory('parseCSV', ['$http', function($http) {
        return $http.get('http://hosting.com/videos/export_projects.csv')
            .success(function(data) {
                return data;
            })
            .error(function(err) {
                return err;
            });
    }]);

mvcApp.controller('indexController_main', ['$scope', '$sce', 'parseCSV', function($scope, $sce, parseCSV) {
    $scope.videos = [];
    parseCSV.success(function(data) {
        $scope.csv = data;
        var lines, lineNumber, data, length;
        lines = $scope.csv.split('\n');
        for(var i = 0; i < lines.length; i++) {
            data = lines[i].split(',');
            var frame = data[0];
            var title = data[1];
            $scope.videos.push({
                frame : frame,
                title : title
            });
        }
    });
    $scope.firstColumnVideos = [];
    $scope.secondColumnVideos = [];
    var init = function() {
        for(var i = 0; i < 3; i++) {
            $scope.firstColumnVideos.push({
                frame: $scope.videos[0].frame,
                title: $scope.videos[0].title
            });
            $scope.videos.splice(0, 1);
            $scope.secondColumnVideos.push({
33.             frame: $scope.videos[0].frame,
                title: $scope.videos[0].title
            });
            $scope.videos.splice(0, 1);
        }
        console.log($scope.firstColumnVideos);
    };
    init();
    $scope.loadMore = function() {
        for(var i = 0; i < 2; i++) {
            $scope.firstColumnVideos.push({
                frame: $scope.videos[0].frame,
                title: $scope.videos[0].title
            });
            $scope.videos.splice(0, 1);
            $scope.secondColumnVideos.push({
                frame: $scope.videos[0].frame,
                title: $scope.videos[0].title
            });
            $scope.videos.splice(0, 1);
        }
    };
    $scope.putIframe = function(video) {
        return $sce.trustAsHtml(video.frame);
    };
}]);

Answer №1

parseCSV.success is a function that operates asynchronously, meaning the data retrieval process is not instantaneous. In order to ensure proper functionality, it is necessary to relocate init() within the success callback of parseCSV.


parseCSV.success(function(data) {
        $scope.csv = data;
        var lines, lineNumber, content, length;
        lines = $scope.csv.split('\n');
        for(var i = 0; i < lines.length; i++) {
            content = lines[i].split(',');
            var frame = content[0];
            var title = content[1];
            $scope.videos.push({
                frame : frame,
                title : title
            });
        }
        init();   // move the initialization process here.
    });

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

Navigating to a different page in the app following a document update: a step-by-step guide

I am facing an issue with a page where I am trying to print a specific DIV using the script below... function printReceiptDiv() { var divElements; if (vm.isDLR) { divElements = document.getElementById("DLRreportCont ...

What is the mechanism behind the functionality of the XMLHttpRequest() object?

After spending some time learning JavaScript, I recently delved into AJAX and encountered something unusual that caught my attention. Consider this sample code snippet: var receiveReq = XMLHttpRequest(); //Initialize the asynchronous request. func ...

Having trouble with Angular + Rails combination: Angular can't seem to locate the controller

Issue: I am encountering an error in my Angular / Rails app. When trying to access a Rails controller function from the Angular controller, I receive the following error: Uncaught TypeError: tasks.moveOrder is not a function. Strangely, all other functions ...

Difficulty in implementing jQuery accordion height style using either content or fill option

What I am looking for is to have only one specific div in my accordion (device properties) change its height based on the content. I have also noticed that if I use Firebug to remove the height property of the device div, it adjusts the height correctly. ...

What is the best way to combine elements in an array of strings using commas between each item, but using "and" before the last item?

I have a collection of phrases that looks like this. ['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'...] I am looking for a way to insert these phrases into the text below, separated by commas, with the w ...

Using the WordPress REST API to retrieve pages based on their URLs

Trying to work with the WP REST API on a website that uses user-friendly URLs instead of ID's, which is different from the typical scenario in a RESTful context. I only have the requested URL to use for querying. For example, if a visitor lands on ex ...

Implementing a JSON array to object conversion in an Express REST API

After conducting a test on a REST API using Postman, the outcome was as follows: { "success": true, "message": "success", "data": [ { "id_buku": 9, "judul_bu ...

How to Retrieve Values from Dynamic Arrays in JavaScript Without Specifying Keys

var data = [ { 'Specials 5': 2192, 'dates': '2021-06-14' }, { 'Specials 8': 767, 'dates': '2021-06-16' }, { 'Specials 13': 2264,'dates': '2021-06-18' }, ] ...

What is the goal of JSON.parse(JSON.stringify(x))?

During my recent project work, I stumbled upon the following code snippet: let newParams = JSON.parse(JSON.stringify(initialParams)); I'm curious - what exactly does this code achieve? ...

Illuminate objects using three.js

My expertise in shaders and three.js is limited, however I am currently experimenting with creating a dynamic glowing effect similar to lights being flicked on and off. Currently, I am adjusting the color saturation and lightness which somewhat achieves ...

JavaScript Click Event Not Functioning

I am attempting to create an interactive feature where clicking on any image will either reveal a clear version of the picture if it is blurred, or blur the picture if it is clear. The current issue I am facing is that when I click on a blurred image, it ...

What is the most efficient method for parsing nested objects in AngularJS?

Currently, I am faced with the challenge of utilizing angularjs to parse a complex nested data structure retrieved from a remote server. My main issue lies in accessing the "events" data using the function below: $scope.generate_event = function(){ ...

Choosing elements based on their ng-model attributes using selenium-webdriver

Currently, I am utilizing Ruby along with the gem selenium-webdriver to navigate through a challenging angular form that is beyond my control. My goal is to figure out how to pinpoint elements based on their ng-model attributes. For instance, let's t ...

I am facing difficulties accessing external URLs in a webview within my Ionic Android application

Recently, I encountered an issue with my Ionic app where it opens an external URL in a webview. The app worked perfectly fine when tested on the iOS simulator, but when testing it on the Android simulator, it failed to function correctly. Upon checking the ...

Transforming a hierarchical array into a string based on a specific condition

Seeking assistance in properly formatting data using the reduce method const testData = { a: [1], b: [2, 3, 4], c: [] }; Objective is to convert to: a=1&b=2,3,4 Current output: a=1&b=2,3,4& const createUrlString = params => Object.key ...

Comparing react-intl and react-i18next for internationalizing ReactJS applications

I am in the process of developing a multilanguage application using ReactJS. This application will require a custom dictionary for various languages, as well as automatic formatting for date/time, numbers, and currency. After researching, I have come acro ...

Obtaining the value with JQuery's .change() function

Currently, I am in the process of setting up dynamic drop-down selectors using JQuery. Despite being new to frontend development, I have encountered a challenge with retrieving the value of a dropdown once it has been changed using JQuery. The user flow I ...

Tips for adjusting the position of rows within a v-data-table - moving them both up and down

Is there a way to rearrange rows up and down in the table? I've been using the checkbox feature and the CRUD data table from the documentation, but I haven't found any examples on how to implement row movement. Currently, my v-data-table setup l ...

showing images received via a websocket connection

My current setup involves receiving one image per second through a WebSocket connection. The images are in blob format, and I am unsure of the best way to display them. Should I use an image tag or a video player? And how should I go about showing these ...

Checkbox remains selected even after navigating back

I am currently working on a code that involves using checkboxes. When I click on them, the checkbox value is appended to the URL with a hash. However, when I go back or press the back button, the URL changes but the checkboxes remain checked. Below is the ...