将 HTTP 响应存储为控制器变量

Storing HTTP Response as a Controller Variable

我想知道是否有办法获取 $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

因此,当您在 "success" 内部时,您似乎只能访问 $scope 而不一定可以访问控制器内的变量。

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

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

谢谢。

您遇到问题的原因是 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