angularjs - 将数据从 http 分配给 'this' Controller

标签 angularjs http

我正在尝试调用 $http 并将返回的数据分配给一个变量。目前我有这段代码,它运行良好。

这是在我的 Controller 中:

.controller('sample', ['$scope', '$http', function($scope, $http){
    var ctrl = this;

    $http.get('somejson.json').success(function(data){
         $scope.myData = data;
    });
});

但是,我不想将它分配给 $scope,而是想将它分配给我的 Controller 变量。但是 ctrl 在我的 get 函数中总是未定义的。我在这里错过了什么吗?我尝试从 Angular 阅读文档,但没有运气。谢谢!

这行不通:

.controller('sample', ['$scope', '$http', function($scope, $http){
        var ctrl = this;

        $http.get('somejson.json').success(function(data){
             debugger;// when I type ctrl in console, just to check, ctrl is undefined.
             ctrl.myData = data; // ctrl is undefined. is it possible to do this?
        });
    });

最佳答案

它在这个 fiddle 中完美运行。

 app.controller('myController', ['$scope', '$http', function($scope, $http) {
    var ctrl = this;

    $http.get('https://dl.dropboxusercontent.com/u/94145612/example.json').success(function(data
         ctrl.myData = data; // ctrl is undefined. is it possible to do this?
    });
 }]);

http://jsfiddle.net/r25akef3/1/

关于angularjs - 将数据从 http 分配给 'this' Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933772/

相关文章:

http - 多部分消息可以包含原始二进制内容吗?

java - 400 - 错误的请求 - 请求在语法上不正确

javascript - 使用 AngularJS 从两个不同的 $scopes 添加数字

javascript - 如何从 firebase 获取所有待办事项?

javascript - 预呈现不等待动态页面标题和元标记呈现

HTTP 内容协商/压缩 : Use Base64 with Accept-Encoding/Content-Encoding?

php - nginx 映射接受 header 到 api 奇怪行为的子目录

node.js - Karma 安装在重建 npm node.js 时失败

angularjs - Node API - 如何将 Facebook 登录链接到 Angular 前端?

javascript - 在javascript中异步使用分块数据