我在一个简单的项目中使用 Angular,并且我达到了可以开始将内容拆分为单独的编码文件的开发状态。
所以,我有一个带有对象数组的变量,称为 oink,如果在我有主模块、 Controller 等的同一个 js 文件中定义,它可以正常工作,但如果我尝试从中导入它外部 json,它不起作用。
我正在使用 http://协议(protocol)。
代码如下:
var oink;
$.getJSON("exemplo.json", function(json) {
oink = json;
});
在我的json文件中
[
{
"brand": "Mooo",
"model": "Moolicious"
},
{
"brand": "Mooo2",
"model": "Moolicious2"
},
{
"brand": "Mooo3",
"model": "Moolicious3"
}
]
添加了应用程序的简化版本:
(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;
});
})();
感谢您的帮助。
最佳答案
oink
在您的 Controller 尝试将其分配给 this.oinky
时将是未定义的。不会创建任何引用,因此当 ajax 更新 oink
时, Controller 变量对此一无所知。
我不知道为什么 getJSON
在 Angular 代码之外。把它放在里面会有帮助
尝试:
app.controller('animalController', function($http){
var self = this;
$http.get("exemplo.json").then(function(response){
self.oinky = response.data
});
});
关于javascript - 无法将json导入Angular中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32158168/