0

it's my first time here on stack and I hope someone can help me because I'm stuck!

I have a script made in AngularJS that creates multiples icons extracting the data from a simple array. Every icon is associated to a youtube video.

The array and the function is simple:

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 I would like to load the array from an external JSON file.

I've tried in any way possible, but didn't work. How I can do it? And how should the JSON file be composed? In every example I've see there are at least two or three values that makes one record, or a pair made with "label":"value".

Thank you so much!!

Ryan Buchmeier
  • 147
  • 1
  • 8
Elio
  • 1
  • 1
  • Quite a bit of info here, depends if it needs to be a file or is a JSON resource on a server somewhere: http://stackoverflow.com/questions/16930473/angularjs-factory-http-get-json-file – PeterS May 25 '16 at 19:59

2 Answers2

0

An array alone is not valid JSON so you'll have to embed the array inside of a parent JSON object like so:

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

And then you'd access the array by referencing videos.videoArray

disperse
  • 1,216
  • 10
  • 22
  • so the json file will include also "var videos =" ? Or is just the data without the var declaration? Sorry.. I'm a newbie! – Elio May 25 '16 at 19:33
  • Depends on how you're serving up the JSON. If you're simply adding another .js file in a script declaration then you'll need the "var videos =" part. If you're serving up the JSON through a web service than you'll send the JSON as-is, without the var declaration. – disperse May 25 '16 at 19:43
0

JSon Format

Disperse is right with the composition of the json format ( $scope.videos = {'keyToArray':['foo','bar','baz',]} ). Also, while I am somewhat new as well, I think disperse has a point using just var instead of $scope. because you don't need it to be in scope if you are just creating a variable and then crunching it later down in your function.

Load data from file

Judging by your unused $http service, I think you may be asking about how to get the data from a .json file you have stored? For that, do something along the following:

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

Hope this helps!

Ryan Buchmeier
  • 147
  • 1
  • 8