Javascript 控制器内的$http函数作用域

Javascript 控制器内的$http函数作用域,javascript,angularjs,model-view-controller,controller,scope,Javascript,Angularjs,Model View Controller,Controller,Scope,我在尝试将“this”与控制器中的角度函数(特别是$http.get)一起使用时遇到问题 例如: Javascript-(psuedo代码) HTML- <div ng-controller='testController as test'> {{test.Stuff}} </div> {{test.Stuff} 当试图访问html中的test.Stuff时,它是空的 我知道存在范围问题,但我是否应该能够访问$http函数中控制器的“this”?请尝试以下方法: c

我在尝试将“this”与控制器中的角度函数(特别是$http.get)一起使用时遇到问题

例如:

Javascript-(psuedo代码)

HTML-

<div ng-controller='testController as test'>
{{test.Stuff}}
</div>

{{test.Stuff}
当试图访问html中的test.Stuff时,它是空的

我知道存在范围问题,但我是否应该能够访问$http函数中控制器的“this”?

请尝试以下方法:

controller('testController')
{
   var self = this;

   $http.get(data)
  {
     self.Stuff = data;
  }
}
我通常使用如下范围:

.controller('testController', function($scope) {
{
   $http.get(data)
  {
     $scope.Stuff = data;
  }
})
试着这样做:

controller('testController')
{
   var self = this;

   $http.get(data)
  {
     self.Stuff = data;
  }
}
我通常使用如下范围:

.controller('testController', function($scope) {
{
   $http.get(data)
  {
     $scope.Stuff = data;
  }
})

您会注意到,成功回调中的
这个
引用了
窗口(全局对象)。正在使用
窗口
作为上下文调用成功回调,因为不是其他函数成员的函数是使用
窗口
对象作为函数的上下文调用的。如果希望
引用控制器实例,则必须将该上下文绑定到函数。您可以使用来完成此任务

.controller('testController')
{
   $http.get(data).success(angular.bind(this, function(data) {
     this.Stuff = data;
  }));
}

您会注意到,成功回调中的
这个
引用了
窗口(全局对象)。正在使用
窗口
作为上下文调用成功回调,因为不是其他函数成员的函数是使用
窗口
对象作为函数的上下文调用的。如果希望
引用控制器实例,则必须将该上下文绑定到函数。您可以使用来完成此任务

.controller('testController')
{
   $http.get(data).success(angular.bind(this, function(data) {
     this.Stuff = data;
  }));
}

在http回调中将数据分配给您的作用域,如下所示:

app.controller('testController',function($scope,$http) {
    $http.get(url).success(function(response) {
        $scope.stuff = response;
    });
});

在http回调中将数据分配给您的作用域,如下所示:

app.controller('testController',function($scope,$http) {
    $http.get(url).success(function(response) {
        $scope.stuff = response;
    });
});

我已经使用了这两种方法,并且知道它们都有效。谢谢你的建议,但它并没有真正回答我的问题。我知道$http内部的“this”发生了变化,但我正试图理解为什么会发生这种变化,因为$http的作用域应该在外部控制器作用域内。您是否在$http回调中放置了一个断点,以查看此
引用了什么。我打赌它引用的是$http服务或窗口,而不是控制器。我已经使用过这两种服务,并且知道它们都可以工作。谢谢你的建议,但它并没有真正回答我的问题。我知道$http内部的“this”发生了变化,但我正试图理解为什么会发生这种变化,因为$http的作用域应该在外部控制器作用域内。您是否在$http回调中放置了一个断点,以查看此
引用了什么。我打赌它引用的是$http服务或窗口,而不是控制器。你测试过这个吗?1.您需要添加数据作为回调参数2。您需要添加另一个右括号3。我没法让它工作,谢谢!这就是答案!你测试过这个吗?1.您需要添加数据作为回调参数2。您需要添加另一个右括号3。我没法让它工作,谢谢!这就是答案!