AngularJS控制器中的'this'与$ scope

雨燕双飞 提交于 2020-08-07 19:26:30

问题:

In the "Create Components" section of AngularJS's homepage , there is this example: AngularJS主页“创建组件”部分中 ,有以下示例:

controller: function($scope, $element) {
  var panes = $scope.panes = [];
  $scope.select = function(pane) {
    angular.forEach(panes, function(pane) {
      pane.selected = false;
    });
    pane.selected = true;
  }
  this.addPane = function(pane) {
    if (panes.length == 0) $scope.select(pane);
    panes.push(pane);
  }
}

Notice how the select method is added to $scope , but the addPane method is added to this . 请注意如何将select方法添加到$scope ,但是将addPane方法添加到this If I change it to $scope.addPane , the code breaks. 如果我将其更改为$scope.addPane ,代码将中断。

The documentation says that there in fact is a difference, but it doesn't mention what the difference is: 该文档说实际上存在区别,但是没有提到区别是什么:

Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. 以前的Angular版本(1.0 RC之前的版本)允许您与$scope方法互换使用this方法,但情况不再如此。 Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope ), but not otherwise inside your controller constructor. 对范围定义的方法里面this$scope是可以互换(角套this$scope ),而不是其他你的控制器构造函数中。

How does this and $scope work in AngularJS controllers? this$scope在AngularJS控制器中如何工作?


解决方案:

参考一: https://stackoom.com/question/mhED/AngularJS控制器中的-this-与-scope
参考二: https://oldbug.net/q/mhED/this-vs-scope-in-AngularJS-controllers
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!