Tips for transferring a value from a JavaScript variable to an AngularJS variable

I am facing an issue with passing a value from a JavaScript variable to an AngularJS variable. I need to send the value stored in the dataArray variable in JavaScript to the AngularJS variable $scope.test

Here is the HTML code snippet:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

     <script src="angular.js"></script>
   <script type='text/javascript'>
 $(document).ready(function () {
   // $("#fileUpload").load('test.csv');
    $.get("test.csv", function(data) {
            alert(data);
            var rows = data.split("\r\n");

                    if(rows.length>0){
                        alert("inside if");
                        var firstRowCells = GetCSVCells(rows[0], ",");

                        var dataArray = new Array();
                        for(var i=1;i<rows.length;i++)
                        {
                            var cells = GetCSVCells(rows[i], ",");
                            var obj = {};
                            for(var j=0;j<cells.length;j++)
                            {
                                obj[firstRowCells[j]] = cells[j];
                            }
                            dataArray.push(obj);
                        }


                        $("#dvCSV").html('');
                        alert(dataArray);
                        $("#dvCSV").append(JSON.stringify(dataArray));
                        var myjson=JSON.stringify(dataArray);
                        //alert(myjson);
                    }

    });
    function GetCSVCells(row, separator){
    return row.split(separator);
}
});


</script>
</head>
<body>
    <div id="container">
        Test
    </div>
<div  ng-app="sortApp" ng-controller="mainController">
    <div id="dvCSV" ng-model="dataf" ng-bind="bdc">dfsgdfd</div>
</div>
<script src="app.js"></script> 
</body>
</html>

The content of app.js file:

angular.module('sortApp', [])
.controller('mainController', function($scope) {
  window.alert("Angular");
  window.alert("asdfad"+$scope.bdc);
  $scope.test=$scope.dataf;
  window.alert($scope.myjson);

  window.alert("test"+$scope.test.value);

Answer №1

One way to incorporate all the jQuery functionality into Angular is by utilizing the HTTP service provided by AngularJS. To get started with a basic HTTP service, you can check out this helpful guide - http://www.w3schools.com/angular/angular_http.asp

Answer №2

I fully support the previous response. It is not recommended to use $(document).ready while also working with the angular framework in your application.

You should consider implementing something similar to this:

angular.module('sortApp', [])
  .service('loadTestCsv' ['$http', function($http) {
    return $http.get('test.csv').then(data => {

     // Perform all necessary data processing
     return data;
    });
  }]); 
  .controller('mainController', ['$scope', 'loadTestCsv', function($scope, loadTestCsv) {
     loadTestCsv().then(data => {
       $scope.data = data;
     });
  }]);

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

Is there a way to convert an array into an object where the first value in the array becomes the name and the properties are an array of the remaining values within subarrays?

Looking to efficiently group elements of a multidimensional array with an unknown list, and transform it into an object while removing duplicate values in the first element of each subarray: For instance, here's the initial array: const arr = [[a, 1 ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Oops! The useNavigate() function can only be utilized within the confines of a <Router> component

I encountered an error while working on my project: An uncaught Error occurred: useNavigate() may only be used within a context of a <Router> component. at invariant (bundle.js:36570:20) at useNavigate (bundle.js:36914:35) at App (bundle. ...

What purpose do controller.$viewValue and controller.$modelValue serve in the Angular framework?

I'm confused about the connection between scope.ngModel and controller.$viewValue/controller.$modelValue/controller.$setViewValue(). I'm specifically unsure of the purpose of the latter three. Take a look at this jsfiddle: <input type="text" ...

Executing the token bucket algorithm

Currently, I am in the process of implementing a token bucket algorithm using JavaScript to keep track of request rates per second. The main goal is to allow requests to go through if there are enough tokens in the bucket, otherwise, the system should enfo ...

Error in GLSL file: "Module parsing error: Unexpected symbol"

I'm currently working on creating a custom image transition using a shader, and I require a fragment.glsl file for this purpose. However, when I try to import this file into my .js file, I encounter the following error: Compiled with problems: ERROR ...

Creating an expand and collapse animation in a `flex` accordion can be achieved even when the container size is fixed using

Good day, I am in need of a fixed-height HTML/CSS/JS accordion. The requirement is for the accordion container's height to be fixed (100% body height) and for any panel content overflow, the scrollbar should appear inside the panel's content div ...

An error was encountered regarding an undefined property while executing NPM and PACT

I'm currently working on implementing the PACT workshop example with some different data. Although this might be more of a Javascript/Node query, I am a bit stuck as a beginner. Here is a snippet from the consumer.spec.js file: const chai = require ...

Double submission issue with Angular form (multiple ajax requests)

My controller seems to be causing a form submission issue in AngularJS where the form is being submitted twice via a get request. Upon checking my database and the console network tab, I noticed that two submissions are logged, with the first submission sh ...

Renaming and destructuring of an array's length using ReactJS

I am working with a reduce function shown below: let el = scopes.reduce ((tot, {actions}) => tot + actions.length, 0); I attempted to modify it as follows, but it appears that this is not the correct approach: let el = scopes.reduce ((tot, {actions.l ...

Sending a tailored query string through a form

Currently, when I submit a form, it directs me to the URL www.domain.com/search/?maxprice=10000000. However, I want it to redirect me to a custom URL such as www.domain.com/search/maxprice_10000000/ I came across some JavaScript code that was supposed to ...

Create a plot marker on a map for every user's location based on their IP

Within my database, there exists a users table that stores each user's IP address. Additionally, I have an API that is capable of retrieving the latitude and longitude coordinates for these users. Initially, the goal is to fetch the latitude and long ...

A guide to toggling SVG elements with AngularJS

Is it possible to toggle between two different svg images using the ng-include directive? For example, I currently have the following code snippet: <i class="indicator oppcicon {{domain.show_requests ? 'icon-chevron-down' : 'icon-chevro ...

Why does `_.map` result in undefined when I return `false`?

I am facing an issue with a function that maps an array using underscore. Below is the function in question: var services = _.map(userCopy.get('services'), function (service) { if (service.service_selected === true) { return service; ...

What steps can I take to ensure my customized tab component can successfully pass an index to its children and effectively hide panes?

I'm currently working on developing a custom Tabs component to enhance my knowledge of React, but I seem to have hit a roadblock. The structure involves three key components that draw inspiration from Material-UI tabs: Tabs, Tab, and TabPane. Tabs.j ...

I'm perplexed by setting up Node.js in order to work with Angular.js

Currently following the Angular tutorial provided at https://docs.angularjs.org/tutorial, but I'm encountering confusion with the Node.js installation. Having already installed node globally on my Mac, the tutorial mentions: The tutorial instructio ...

The image's alternative text or title property is missing, resulting in a blank white space being displayed instead

By adjusting the image option in my browser settings, I was able to render the image. However, upon the initial load, the "alt" or "title" attribute of the image is not displaying and appears as empty white space. Interestingly, after using ctrl+R to refr ...

Guide to compiling an element within a directive using ngModel

I am attempting to create a table cell that can be edited, but there are certain conditions that dictate whether it is editable or not. This means I cannot simply include an input in the template. My objective is for the cell to generate an input using the ...

Encountering a misleading 404 error message from Axios

There seems to be an issue with the axios query function, as it is querying the wrong URL just before sending the query. getShows : function(){ if( ! this.query ) return false; var getURL = this.makeUrlFromObject(this.query); console.log('getUR ...

Combining column values with AngularJS

What is the best way to merge column values in AngularJS? ...