简体   繁体   English

无法将json导入Angular中的变量

[英]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. 我在一个简单的项目中使用angular,我达到了开发状态,我可以开始将内容分成单独的编码文件。

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. 所以,我有一个带有一个对象数组的变量,叫做oink,如果在同一个js文件中定义,我有主模块,控制器等,它可以正常工作,但如果我尝试从外部json导入它,它不起作用。

I'm using the http:// protocol. 我正在使用http://协议。

The code is as follow: 代码如下:

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

and in the json file I have 在我有的json文件中

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

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

Added the app dumbed-down version of the app: 添加了应用程序的应用程序dumbed-down版本:

(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. 谢谢您的帮助。

oink will be undefined at the time your controller tries to assign it to this.oinky . oink将在您的控制器尝试将它指定的时间是不确定的this.oinky No reference will be created so when the ajax updates oink the controller variable knows nothing about it. 将不会创建引用,因此当ajax更新oink ,控制器变量对此一无所知。

I don't know why the getJSON is outside of the angular code. 我不知道为什么getJSON超出了角度代码。 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
      });

});

You may violate the same-origin policy. 您可能违反同源政策。 Read more here if you want to investigate further: "Cross origin requests are only supported for HTTP." 如果您想进一步调查,请在此处阅读更多内容: “仅支持HTTP的跨源请求。” error when loading a local file 加载本地文件时出错

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM