0

got this json file:

[
{
    "name": "paprika",
    "imgSrc": "img/paprika.jpg"
},
{
    "name": "kurkku",
    "imgSrc": "img/kurkku.jpg"
},
{
    "name": "porkkana",
    "imgSrc": "img/porkkana.jpg"
},
{
    "name": "lehtisalaatti",
    "imgSrc": "img/lehtisalaatti.jpg"
},
{
    "name": "parsakaali",
    "imgSrc": "img/parsakaali.jpg"
},
{
    "name": "sipula",
    "imgSrc": "img/sipuli.jpg"
},
{
    "name": "peruna",
    "imgSrc": "img/peruna.jpg"
},
{
    "name": "soijapapu",
    "imgSrc": "img/soijapapu.jpg"
},
{
    "name": "pinaatti",
    "imgSrc": "img/pinaatti.jpg"
}
]

Which I successfully fetch in a factory:

factory('getJson', ['$resource', function($resource) {
    return $resource('json/vegs.json', {}, {
      query: {method:'GET', isArray:true}
    });
  }]);

in my Controller I can get the json's file content:

var vegs = getJson.query();
    $scope.vegs = vegs;
    console.log(vegs)
    console.log(typeof vegs)

The weird part is the first console.log produces an array of objects, as expected. The second console says it's an "object", and not an array.

I can get the .json content to my view using {{vegs}}, and I can use ng-repeat as well, tho in the controller I can't do vegs[0] or vegs.length. It comes out empty.

I'm breaking my head on this for over 3 hours now :)

Shining Love Star
  • 5,734
  • 5
  • 39
  • 49
  • It comes out empty b/c you're accessing the array before the server has responded. Check out [this answer](http://stackoverflow.com/a/18222998/398606)... – Sunil D. Aug 05 '14 at 04:30
  • Actually that answer describes the problem, but doesn't seem to give a proper answer (you should not use `$scope.$watch`, instead use the `$promise` property or [pass in call backs](http://stackoverflow.com/a/16389582/398606). – Sunil D. Aug 05 '14 at 04:39
  • Read the answer that I linked to in my second comment :) In that case they have a resource named "Category" and when they call the `query()` function they pass in callback that will be executed when the server responds successfully. – Sunil D. Aug 05 '14 at 04:44
  • Works! Can't seem to credit your comment tho :) – Shining Love Star Aug 05 '14 at 04:51
  • This is actually a common problem, and I was too lazy to type an actual answer so I really don't deserve any credit... You might up vote the answer that I linked to instead :) – Sunil D. Aug 05 '14 at 04:54

1 Answers1

1

This isn't an 'answer'. Just an observation on one part of your issue. (Sorry, can't comment yet...new to stackoverflow).

Just a note on your comment that "The second console says it's an "object", and not an array." Using typeof on an array will always return "object".

There are various (and debated, it seems) ways to test if it's an array--Array.isArray(obj) for example.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

smw
  • 1,033
  • 9
  • 6