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

Angularjs 将HTTP响应存储为控制器变量,angularjs,angularjs-scope,angularjs-controller,angularjs-http,Angularjs,Angularjs Scope,Angularjs Controller,Angularjs Http,我想知道是否有一种方法可以接受$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: 'exam

我想知道是否有一种方法可以接受$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”时,我最终遇到的错误是:

因此,当您在“success”中时,您似乎只能访问$scope,而不必访问控制器中的变量

我试图做的是本地化“result”变量的范围,以防我想在其他控制器中使用相同的名称。我想如果我使用$scope,那么我必须跟踪所有控制器中的所有变量

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


谢谢。

您出现问题的原因是
不是指回调中的控制器。有多种方法可以克服这一问题,其中之一是:

$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));

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

出现问题的原因是
不是指回调中的控制器。有多种方法可以克服这一问题,其中之一是:

$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));

有关此主题的更多信息,请参阅此部分。

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