我试图让 Controller 在使用时从服务器检索其数据,但由于某种原因,这似乎无法正常工作:
app.controller('eventListController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
var eventList = this,
getEventList = function () {
var promise = $http.get('../json/Login.json');
promise.then(function (response) {
eventList = response.data;
}, function (error) {
window.alert('Error' + error);
});
};
getEventList();
}]);
看起来很简单,但 eventList 无法正确加载
我做错了什么?
JSON 大致如下
{
"eventHead": [
{
stuff stuff
},
{
more stuff
}
],
"success": true
}
如果我做一个
window.alert(eventList);
之后
getEventList();
我得到[object Object],这看起来很正常
但如果我这样做
window.alert(eventList.success);
我未定义
而且我的数据没有加载到页面
最佳答案
您不想用结果覆盖 this
(您的 Controller )的引用(编辑:我的意思是,您不再引用 Controller ,而只是引用数据- 在 View 中无法访问)。您想在 Controller 上设置一个属性 - 我认为您正在使用 controller as
语法?这会更好地实现我认为您想要实现的目标:
app.controller('eventListController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
var that = this;
var getEventList = function () {
var promise = $http.get('../json/Login.json');
promise.then(function (response) {
that.eventList = response.data;
}, function (error) {
console.log('Error', error);
});
};
getEventList();
}]);
编辑:已经多次向我指出,上述(问题)语法是正确的。我同意——这只是不好的做法。您不应该使用 , 和换行符定义多个变量。我认为大多数 javascript 开发人员都会同意它不会增加可读性(我认为我的误读证明了这一点)。
关于javascript - AngularJS Controller 无法加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38266531/