Pedro Marta
Pedro Marta

Reputation: 45

Can't import json to a variable in Angular

I am working with angular in a simple project and I reached the state of development where I can start to split the content into separate files of the coding.

So, I have a variable with an array of objects, called oink, that if defined in the same js file where I have the main module, controller and so on, it works properly, but if I try to import it from an external json, it doesn't work.

I'm using the http:// protocol.

The code is as follow:

var oink;
$.getJSON("exemplo.json", function(json) {
  oink = json;
});

and in the json file I have

[
 {
    "brand": "Mooo",
    "model": "Moolicious"
  },
 {
  "brand": "Mooo2",
  "model": "Moolicious2"

  },
  {
  "brand": "Mooo3",
  "model": "Moolicious3"
  }
]

Added the app dumbed-down version of the app:

(function() {
var app = angular.module('farm', []);

app.controller('animalController', function(){
this.oinky = oink;

 });

app.controller('TabController', function(){
this.tab = 1;

this.setTab = function(newValue){
  this.tab = newValue;
};

this.isSet = function(tabmodel){
  return this.tab === tabmodel;
};

this.tier = 1;

this.setTier = function(newValue){
  this.tier = newValue;
};

this.tierSet = function(tiermodel){
  return this.tier === tiermodel;
};

this.show = -1;

this.defineBox= function(janein){

  if(this.show>-1 && this.show==janein) {
    this.show=-1;
  } else {
    this.show=janein;
  }
};

this.currentBox = function(janein) {
  return this.show === janein;
};

this.slide = 1;

this.defineSlide= function(number){
    this.slide = number;
};

this.currentSlide= function(number) {
  return this.slide === number;
};

});



var oink;
$.getJSON("exemplo.json", function(json) {
 oink = json;
});




})();

Thanks for the help.

Upvotes: 3

Views: 164

Answers (2)

quanfoo
quanfoo

Reputation: 365

You may violate the same-origin policy. Read more here if you want to investigate further: "Cross origin requests are only supported for HTTP." error when loading a local file

Upvotes: -2

charlietfl
charlietfl

Reputation: 171679

oink will be undefined at the time your controller tries to assign it to this.oinky. No reference will be created so when the ajax updates oink the controller variable knows nothing about it.

I don't know why the getJSON is outside of the angular code. Putting it inside would help

Try:

app.controller('animalController', function($http){
      var self = this;
      $http.get("exemplo.json").then(function(response){
         self.oinky = response.data
      });

});

Upvotes: 3

Related Questions