【发布时间】: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