Importing data from an external file into an array using AngularJS

Hey there, I'm new here on Stack and hoping someone can lend a hand because I've hit a roadblock!

I'm working with an AngularJS script that generates multiple icons using data from a simple array. Each icon is linked to a YouTube video.

The code snippet below shows how straightforward the array and function are:

app.controller('videolist', function ($scope, $http) {
$scope.videos = ['q_664lrmyGE','q_664lrmyGE','dWuEVSCw8B8','3Wm3G8s8bxk','_ppuCZR8Mkw','9gN_cmK9TUc','s7lVGhTPQAY','_rNmmHXEdTc','blr-qDffIq0','_70M4lkLKPk','wjB9JtTU7SU','BGh1xc-O0WA','uxEBK9q686c','ToO-tS-X2U4','AKrmrbCTNxc'];

$scope.icon = [];
  // add youtube videos
  for (i=0; i<$scope.videos.length; i++) {
    $scope.icon.push({id: $scope.videos[i], thumb: 'mqdefault'});

  }
});

Now my goal is to load the array from an external JSON file.

I've attempted various methods, but none seem to be successful. How can I achieve this? And what should the structure of the JSON file look like? Most examples I've come across have records with two or three values, often in a "label":"value" pair.

Any guidance would be greatly appreciated!!

Answer №1

If you have an array that is not valid JSON, you can solve this issue by embedding the array within a parent JSON object. Here's how:

var videos = {'videoArray':['q_664lrmyGE','q_664lrmyGE','dWuEVSCw8B8',...]}

To access the contents of the array, simply reference videos.videoArray

Answer №2

Working with JSON

Understanding the structure of JSON format is crucial, as pointed out by Disperse in the example code

$scope.videos = {'keyToArray':['foo','bar','baz',]}
. It's worth considering using var instead of $scope. for variables that don't need to be accessed globally, especially when processing data within a function.

Importing Data from External Files

If you're looking to retrieve data from a .json file, utilizing the unused $http service can help. Try the following approach:

$http.get("video.json").then(function (response) {
    $scope.videos = response.data;
});

Hopefully, this solution proves helpful for your task!

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

Prevent the selection of rows and only enable the option to select checkboxes in PrimeNG's Multiselect feature

I'm currently working on a task that involves using PrimeNG multiselect. This particular multiselect includes checkboxes followed by text within each row. I need to disable the ability to select rows by clicking on the text, and instead only allow sel ...

Determine future dates based on selected date and time

When a user selects a date in the datetimepicker, I want to automatically set three additional dates. The first date will be the selected date + 28 days, the second date will be selected date + 56 days, and the third date will be selected date + 84 days. I ...

Having trouble converting JSON to an object with Newtonsoft.Json library

I have encountered an issue with deserializing a sample JSON received from a service using C#. { "columns": [ "empid", "employeename", "currentAllocation", "Dept head", ...

Angular template src variable issue with no solution in sight

The videoSrc variable is not evaluating correctly images/{{videoSrc}}.mp4 When I write just videoSrc, it works fine. But when I concatenate it with other strings, it doesn't work. Check out this jsfiddle ...

What is the process for dynamically altering the method in a class?

Is there a way to dynamically modify the changeThis method by substituting it with the value of a radio element? For example, if I select event1, the method should be switched to Class.event1() <input type="radio" class="radio-input" ...

JavaScript/jQuery Tutorial: Accessing the src attribute of images sharing a common class名

How can I extract the src values of images with the same class and display them in an empty div? For instance: <body> <img class="class1" src="http://www.mysite.com/img/image1.jpg" width="168" height="168" alt=""> <img class="class ...

Exploring the depths of JSON parsing with Java's speedy FastXML library

Experimenting with a Java program to test JSON Processing using the org.fasterxml.jackson.core and the jackson-databind libraries in a streaming manner. The main objective is to understand how to handle JSON data and extract specific information. Currently ...

How to Retrieve Superclass Fields in Angular 5 Component

I have a superclass that provides common functionality for components. export class AbstractComponent implements OnInit { public user: User; constructor(public http: HttpClient) { } ngOnInit(): void { this.http.get<User>(& ...

Ways to make the background color white in Bootstrap 5

Can someone assist me in changing the background color of my portfolio to white? I attempted to use global CSS, but the black background on both sides of the page is preventing the change. return ( <> <Navbar /> <main className= ...

What is the best way to send multiple arrays of JSON objects to a Stimulsoft report using JavaScript?

I am currently working with this JavaScript code snippet: var viewer = new window.Stimulsoft.Viewer.StiViewer( null, "StiViewer", false ); var report = new window.Stimulsoft.Report.StiReport(); const { data: reportData } = await GetRequest ...

What might be causing the status problem to not display correctly?

My toggle feature to switch between no issue and issue is not displaying the status correctly. Despite trying to troubleshoot, I can't figure out why the issue section is not showing up. <!DOCTYPE html> <html> <script src="https://aj ...

Unexpected issue with sliding menu toggle implementation

I have been struggling to make a menu slide to the left when a button is clicked, and then slide back to its original position when the same button is clicked again. Although I have been using the toggle method, it doesn't seem to be working for me. I ...

Make sure to verify a user's "clearance level" before entering a page

Recently delving into the world of node.js, I encountered a simple issue: In my routes file, there is a function that verifies if a user is authenticated. function isLoggedIn(req, res, next) { if(req.isAuthenticated()){ console.log(req.user); ...

Issue encountered while compiling all handlebars templates into a single JavaScript file

Below is the structure of my folders: app └───templates ├───templ1.hbs ├───templ2.hbs └───templ3.hbs I am looking to compile (precompile) all templN.hbs handlebars template files into one templ.js file. However ...

Why is the Axios instance/function not being passed the argument?

I am currently working on refactoring a next.js App that has a functioning axios call. However, I have encountered an issue with my new function not receiving arguments. The problem consists of two main components: my next.js page and an external custom m ...

Having trouble injecting dependencies into a Jasmine test, as I'm receiving the following error message: "$injector:unpr Unknown provider: appConfigProvider <- appConfig"

I've been working on creating a Jasmine test, but I'm having trouble with injecting dependencies declared in the 'myApp' module. When trying to inject the dependency (constant) value appConfig, I encounter the following error: Error: [ ...

NgFor is failing to display data from a fully populated array of objects

CLICK HERE FOR THE IMAGE So, let's tackle the issue at hand. I have an array that contains data fetched from an API. These data points are essentially messages. Now, below is the TypeScript file for a component where I aim to display all these messag ...

What is the most effective way to retrieve data from a URL and process it using reactjs?

Looking to consume JSON data from a URL, here is an example of the JSON structure: { "results": [ ... ], "info": { ... } } I aim to display the fetched data as a component property. What is the most efficient way to achie ...

I was working with node.js when I encountered the following issue: 'server' is declared but its value is never read.ts(6133) from the line "var server = app.listen(3000, listening);"

While working on the 8.6 lesson in the api2 folder, I encountered an error/bug. Upon inspection of my server.js file, I identified and rectified the issue. However, when I revisited the api1 folder for the 8.5 lesson, everything was functioning correctly a ...

Filtering objects in JavaScript using a technique similar to list comprehension

I'm dealing with a basic array structure that resembles: obj = {1:false, 2:true, 3:true} My goal is to extract an array containing all the keys in the object that have a value of true. In Python, you can achieve this easily using: >>> [ke ...