简体   繁体   English

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

[英]Angular $http function scope inside controller

I'm having a problem trying to use "this" with angular functions (specifically $http.get) inside a controller. 我在尝试在控制器内的角度函数(特别是$ http.get)中使用“ this”时遇到问题。

Example: 例:

Javascript- (psuedo code) Javascript-(伪代码)

...
.controller('testController')
{
   $http.get(data)
  {
     this.Stuff = data;
  }
}
...

HTML- HTML-

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

When trying to access test.Stuff in the html, it is empty. 尝试访问html中的test.Stuff时,它为空。

I understand that there is a scope issue, but shouldn't I be able to access the controller's 'this' inside of the $http function? 我知道存在范围问题,但是我不应该能够在$ http函数内部访问控制器的“ this”吗?

You'll notice that this inside of your success callback refers to window (the global object). 您会注意到,成功回调内部的this对象引用window (全局对象)。 Your success callback is being called with window as the context because functions that are not members of other functions are invoked with the window object as the context for the function. 您将以window为上下文来调用成功回调,因为不是其他函数成员的函数都以window对象作为函数的上下文来调用。 If you want this to refer to your controller instance you must bind that context to the function. 如果希望this引用您的控制器实例,则必须将该上下文绑定到该函数。 You can use angular.bind to accomplish this. 您可以使用angular.bind完成此操作。

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

Try it this way: 尝试这种方式:

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

   $http.get(data)
  {
     self.Stuff = data;
  }
}

I typically use the scope like this: 我通常使用这样的范围:

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

Assign the data to your scope in the http callback like so: 将数据分配给您在http回调中的作用域,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM