问题:
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
thisinterchangeably with the$scopemethod, but this is no longer the case. 以前的Angular版本(1.0 RC之前的版本)允许您与$scope方法互换使用this方法,但情况不再如此。 Inside of methods defined on the scopethisand$scopeare interchangeable (angular setsthisto$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
来源:oschina
链接:https://my.oschina.net/stackoom/blog/4314920