【问题标题】:Storing HTTP Response as a Controller Variable将 HTTP 响应存储为控制器变量
【发布时间】:2015-11-29 22:29:40
【问题描述】:

我想知道是否有办法获取 $http 响应并将其存储到控制器变量而不是 $scope。例如:

app.controller('testController', function($scope, $http) {

    this.result = 5; // I'd like to store the result here instead of on $scope

    $http({
            method: 'POST',
            url: 'example/',
            params: {test_param :'test_parameter'}
        }).success(function(result) {
            $scope.result = result.data; // This works
            this.result = result.data; // This does not work
        });

我在尝试使用“this.result”时最终得到的错误是:

TypeError: Cannot set property 'result' of undefined

因此,当您处于“成功”状态时,您似乎只能访问 $scope 而不一定访问控制器中的变量。

我想要做的是本地化“结果”变量的范围,以防我想在其他控制器中使用相同的名称。我想如果我使用 $scope 那么我将不得不跟踪所有控制器中的所有变量?

无论如何,我觉得我在这里使用了错误的模型,但我们将不胜感激。

谢谢。

【问题讨论】:

  • 请注意,您不需要将变量保存为控制器的实例变量。一个局部变量就可以了。只需使用var result = 5;result = response.data; 即可(当然,成功回调的result 参数必须重命名以避免冲突)。

标签: angularjs angularjs-scope angularjs-controller angularjs-http


【解决方案1】:

您的问题的原因是 this 不是指回调中的控制器。有多种方法可以解决这个问题,其中之一是:

$http({
    method: 'POST',
    url: 'example/',
    params: { test_param: 'test_parameter' }
}).success(function(result) {
    $scope.result = result.data; // This works
    this.result = result.data; // Should also work now
}.bind(this));

有关该主题的更多信息,请参阅此question

【讨论】:

    猜你喜欢
    • 2016-08-25
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多