javascript - AngularJS Controller 无法加载数据

标签 javascript angularjs

我试图让 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/

相关文章:

javascript - 如何使用 Bootstrap 打开模态中的所有链接

javascript - Angular 地理编码结果不同步

angularjs - 当我包含 JQuery 时出现警告 : Tried to load angular more than once.

javascript - 将 arraybuffer 从 angularjs 发送到 C# 端点

javascript - 谷歌加一个按钮

javascript - 用不同的图像/按钮替换图像 - javascript

javascript - 当 gulp 为应用程序提供服务时,如何在 webstorm 中调试 Javascript

javascript - PassFactory.setNewPass 不是函数,工厂函数不是函数

javascript - Angular ngMessages 对模糊的验证取消了链接/按钮点击

javascript - 对 nodejs 服务器的 jquery ajax 请求仅适用于页面刷新